Merge branch 'main' into nate/fixees
This commit is contained in:
commit
114b7f1bf6
166 changed files with 3026 additions and 3764 deletions
|
|
@ -28,11 +28,10 @@ Example:
|
|||
```json title="config.json"
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "Qwen2.5-Coder 1.5b",
|
||||
"model": "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF",
|
||||
"provider": "lmstudio",
|
||||
},
|
||||
...
|
||||
"title": "Qwen2.5-Coder 1.5b",
|
||||
"model": "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF",
|
||||
"provider": "lmstudio"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { getUriFileExtension } from "../../util/uri";
|
||||
import { BracketMatchingService } from "../filtering/BracketMatchingService";
|
||||
import {
|
||||
CharacterFilter,
|
||||
|
|
@ -27,7 +28,7 @@ export const Python = {
|
|||
name: "Python",
|
||||
// """"#" is for .ipynb files, where we add '"""' surrounding markdown blocks.
|
||||
// This stops the model from trying to complete the start of a new markdown block
|
||||
topLevelKeywords: ["def", "class", "\"\"\"#"],
|
||||
topLevelKeywords: ["def", "class", '"""#'],
|
||||
singleLineComment: "#",
|
||||
endOfLine: [],
|
||||
};
|
||||
|
|
@ -368,8 +369,7 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
|
|||
md: Markdown,
|
||||
};
|
||||
|
||||
export function languageForFilepath(
|
||||
filepath: string,
|
||||
): AutocompleteLanguageInfo {
|
||||
return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript;
|
||||
export function languageForFilepath(fileUri: string): AutocompleteLanguageInfo {
|
||||
const extension = getUriFileExtension(fileUri);
|
||||
return LANGUAGES[extension] || Typescript;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,20 +18,20 @@ import { AutocompleteSnippetDeprecated } from "../../types";
|
|||
import { AstPath } from "../../util/ast";
|
||||
import { ImportDefinitionsService } from "../ImportDefinitionsService";
|
||||
|
||||
function getSyntaxTreeString(
|
||||
node: Parser.SyntaxNode,
|
||||
indent: string = "",
|
||||
): string {
|
||||
let result = "";
|
||||
const nodeInfo = `${node.type} [${node.startPosition.row}:${node.startPosition.column} - ${node.endPosition.row}:${node.endPosition.column}]`;
|
||||
result += `${indent}${nodeInfo}\n`;
|
||||
// function getSyntaxTreeString(
|
||||
// node: Parser.SyntaxNode,
|
||||
// indent: string = "",
|
||||
// ): string {
|
||||
// let result = "";
|
||||
// const nodeInfo = `${node.type} [${node.startPosition.row}:${node.startPosition.column} - ${node.endPosition.row}:${node.endPosition.column}]`;
|
||||
// result += `${indent}${nodeInfo}\n`;
|
||||
|
||||
for (const child of node.children) {
|
||||
result += getSyntaxTreeString(child, indent + " ");
|
||||
}
|
||||
// for (const child of node.children) {
|
||||
// result += getSyntaxTreeString(child, indent + " ");
|
||||
// }
|
||||
|
||||
return result;
|
||||
}
|
||||
// return result;
|
||||
// }
|
||||
|
||||
export class RootPathContextService {
|
||||
private cache = new LRUCache<string, AutocompleteSnippetDeprecated[]>({
|
||||
|
|
|
|||
|
|
@ -1,8 +1,6 @@
|
|||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import MockLLM from "../../../llm/llms/Mock";
|
||||
import { testConfigHandler, testIde } from "../../../test/fixtures";
|
||||
import { joinPathsToUri } from "../../../util/uri";
|
||||
import { CompletionProvider } from "../../CompletionProvider";
|
||||
import { AutocompleteInput } from "../../util/types";
|
||||
|
||||
|
|
@ -39,8 +37,8 @@ export async function testAutocompleteFiltering(
|
|||
|
||||
// Create a real file
|
||||
const [workspaceDir] = await ide.getWorkspaceDirs();
|
||||
const filepath = path.join(workspaceDir, test.filename);
|
||||
fs.writeFileSync(filepath, test.input.replace(FIM_DELIMITER, ""));
|
||||
const fileUri = joinPathsToUri(workspaceDir, test.filename);
|
||||
await ide.writeFile(fileUri, test.input.replace(FIM_DELIMITER, ""));
|
||||
|
||||
// Prepare completion input and provider
|
||||
const completionProvider = new CompletionProvider(
|
||||
|
|
@ -56,7 +54,7 @@ export async function testAutocompleteFiltering(
|
|||
const autocompleteInput: AutocompleteInput = {
|
||||
isUntitledFile: false,
|
||||
completionId: "test-completion-id",
|
||||
filepath,
|
||||
filepath: fileUri,
|
||||
pos: {
|
||||
line,
|
||||
character,
|
||||
|
|
|
|||
|
|
@ -3,9 +3,9 @@ import path from "node:path";
|
|||
import ignore from "ignore";
|
||||
|
||||
import { IDE } from "../..";
|
||||
import { getBasename } from "../../util";
|
||||
import { getConfigJsonPath } from "../../util/paths";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
import { findUriInDirs } from "../../util/uri";
|
||||
|
||||
async function isDisabledForFile(
|
||||
currentFilepath: string,
|
||||
|
|
@ -15,26 +15,14 @@ async function isDisabledForFile(
|
|||
if (disableInFiles) {
|
||||
// Relative path needed for `ignore`
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
let filepath = currentFilepath;
|
||||
for (const workspaceDir of workspaceDirs) {
|
||||
const relativePath = path.relative(workspaceDir, filepath);
|
||||
const relativePathBase = relativePath.split(path.sep).at(0);
|
||||
const isInWorkspace =
|
||||
!path.isAbsolute(relativePath) && relativePathBase !== "..";
|
||||
if (isInWorkspace) {
|
||||
filepath = path.relative(workspaceDir, filepath);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Worst case we can check filetype glob patterns
|
||||
if (filepath === currentFilepath) {
|
||||
filepath = getBasename(filepath);
|
||||
}
|
||||
const { relativePathOrBasename } = findUriInDirs(
|
||||
currentFilepath,
|
||||
workspaceDirs,
|
||||
);
|
||||
|
||||
// @ts-ignore
|
||||
const pattern = ignore.default().add(disableInFiles);
|
||||
if (pattern.ignores(filepath)) {
|
||||
if (pattern.ignores(relativePathOrBasename)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { IDE } from "../../index";
|
||||
import { findUriInDirs } from "../../util/uri";
|
||||
import { ContextRetrievalService } from "../context/ContextRetrievalService";
|
||||
import { GetLspDefinitionsFunction } from "../types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
|
@ -45,7 +46,9 @@ async function getIdeSnippets(
|
|||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
|
||||
return ideSnippets.filter((snippet) =>
|
||||
workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)),
|
||||
workspaceDirs.some(
|
||||
(dir) => !!findUriInDirs(snippet.filepath, [dir]).foundInDir,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
// Fill in the middle prompts
|
||||
|
||||
import { CompletionOptions } from "../../index.js";
|
||||
import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js";
|
||||
import {
|
||||
getLastNUriRelativePathParts,
|
||||
getShortestUniqueRelativeUriPaths,
|
||||
} from "../../util/uri.js";
|
||||
import {
|
||||
AutocompleteCodeSnippet,
|
||||
AutocompleteSnippet,
|
||||
|
|
@ -15,6 +18,7 @@ export interface AutocompleteTemplate {
|
|||
filepath: string,
|
||||
reponame: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
workspaceUris: string[],
|
||||
) => [string, string];
|
||||
template:
|
||||
| string
|
||||
|
|
@ -25,6 +29,7 @@ export interface AutocompleteTemplate {
|
|||
reponame: string,
|
||||
language: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
workspaceUris: string[],
|
||||
) => string);
|
||||
completionOptions?: Partial<CompletionOptions>;
|
||||
}
|
||||
|
|
@ -73,25 +78,32 @@ const codestralFimTemplate: AutocompleteTemplate = {
|
|||
|
||||
const codestralMultifileFimTemplate: AutocompleteTemplate = {
|
||||
compilePrefixSuffix: (
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
filepath: string,
|
||||
reponame: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
prefix,
|
||||
suffix,
|
||||
filepath,
|
||||
reponame,
|
||||
snippets,
|
||||
workspaceUris,
|
||||
): [string, string] => {
|
||||
if (snippets.length === 0) {
|
||||
if (suffix.trim().length === 0 && prefix.trim().length === 0) {
|
||||
return [`+++++ ${getLastNPathParts(filepath, 2)}\n${prefix}`, suffix];
|
||||
return [
|
||||
`+++++ ${getLastNUriRelativePathParts(workspaceUris, filepath, 2)}\n${prefix}`,
|
||||
suffix,
|
||||
];
|
||||
}
|
||||
return [prefix, suffix];
|
||||
}
|
||||
|
||||
const relativePaths = shortestRelativePaths([
|
||||
...snippets.map((snippet) =>
|
||||
"filepath" in snippet ? snippet.filepath : "Untitled.txt",
|
||||
),
|
||||
filepath,
|
||||
]);
|
||||
const relativePaths = getShortestUniqueRelativeUriPaths(
|
||||
[
|
||||
...snippets.map((snippet) =>
|
||||
"filepath" in snippet ? snippet.filepath : "file:///Untitled.txt",
|
||||
),
|
||||
filepath,
|
||||
],
|
||||
workspaceUris,
|
||||
);
|
||||
|
||||
const otherFiles = snippets
|
||||
.map((snippet, i) => {
|
||||
|
|
@ -136,12 +148,13 @@ const codegemmaFimTemplate: AutocompleteTemplate = {
|
|||
// https://arxiv.org/pdf/2402.19173.pdf section 5.1
|
||||
const starcoder2FimTemplate: AutocompleteTemplate = {
|
||||
template: (
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
filename: string,
|
||||
reponame: string,
|
||||
language: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
prefix,
|
||||
suffix,
|
||||
filename,
|
||||
reponame,
|
||||
language,
|
||||
snippets,
|
||||
workspaceUris,
|
||||
): string => {
|
||||
const otherFiles =
|
||||
snippets.length === 0
|
||||
|
|
@ -189,21 +202,22 @@ const deepseekFimTemplate: AutocompleteTemplate = {
|
|||
// https://github.com/THUDM/CodeGeeX4/blob/main/guides/Infilling_guideline.md
|
||||
const codegeexFimTemplate: AutocompleteTemplate = {
|
||||
template: (
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
filepath: string,
|
||||
reponame: string,
|
||||
language: string,
|
||||
allSnippets: AutocompleteSnippet[],
|
||||
prefix,
|
||||
suffix,
|
||||
filepath,
|
||||
reponame,
|
||||
language,
|
||||
allSnippets,
|
||||
workspaceUris,
|
||||
): string => {
|
||||
const snippets = allSnippets.filter(
|
||||
(snippet) => snippet.type === AutocompleteSnippetType.Code,
|
||||
) as AutocompleteCodeSnippet[];
|
||||
|
||||
const relativePaths = shortestRelativePaths([
|
||||
...snippets.map((snippet) => snippet.filepath),
|
||||
filepath,
|
||||
]);
|
||||
const relativePaths = getShortestUniqueRelativeUriPaths(
|
||||
[...snippets.map((snippet) => snippet.filepath), filepath],
|
||||
workspaceUris,
|
||||
);
|
||||
const baseTemplate = `###PATH:${
|
||||
relativePaths[relativePaths.length - 1]
|
||||
}\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { getLastNPathParts } from "../../util";
|
||||
import { getLastNUriRelativePathParts } from "../../util/uri";
|
||||
import {
|
||||
AutocompleteClipboardSnippet,
|
||||
AutocompleteCodeSnippet,
|
||||
|
|
@ -14,32 +14,34 @@ const getCommentMark = (helper: HelperVars) => {
|
|||
|
||||
const addCommentMarks = (text: string, helper: HelperVars) => {
|
||||
const commentMark = getCommentMark(helper);
|
||||
const lines = [
|
||||
...text
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => `${commentMark} ${line}`),
|
||||
];
|
||||
|
||||
return lines.join("\n");
|
||||
return text
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => `${commentMark} ${line}`)
|
||||
.join("\n");
|
||||
};
|
||||
|
||||
const formatClipboardSnippet = (
|
||||
snippet: AutocompleteClipboardSnippet,
|
||||
workspaceDirs: string[],
|
||||
): AutocompleteCodeSnippet => {
|
||||
return formatCodeSnippet({
|
||||
filepath: "Untitled.txt",
|
||||
content: snippet.content,
|
||||
type: AutocompleteSnippetType.Code,
|
||||
});
|
||||
return formatCodeSnippet(
|
||||
{
|
||||
filepath: "file:///Untitled.txt",
|
||||
content: snippet.content,
|
||||
type: AutocompleteSnippetType.Code,
|
||||
},
|
||||
workspaceDirs,
|
||||
);
|
||||
};
|
||||
|
||||
const formatCodeSnippet = (
|
||||
snippet: AutocompleteCodeSnippet,
|
||||
workspaceDirs: string[],
|
||||
): AutocompleteCodeSnippet => {
|
||||
return {
|
||||
...snippet,
|
||||
content: `Path: ${getLastNPathParts(snippet.filepath, 2)}\n${snippet.content}`,
|
||||
content: `Path: ${getLastNUriRelativePathParts(workspaceDirs, snippet.filepath, 2)}\n${snippet.content}`,
|
||||
};
|
||||
};
|
||||
|
||||
|
|
@ -49,10 +51,6 @@ const formatDiffSnippet = (
|
|||
return snippet;
|
||||
};
|
||||
|
||||
const getCurrentFilepath = (helper: HelperVars) => {
|
||||
return getLastNPathParts(helper.filepath, 2);
|
||||
};
|
||||
|
||||
const commentifySnippet = (
|
||||
helper: HelperVars,
|
||||
snippet: AutocompleteSnippet,
|
||||
|
|
@ -66,9 +64,10 @@ const commentifySnippet = (
|
|||
export const formatSnippets = (
|
||||
helper: HelperVars,
|
||||
snippets: AutocompleteSnippet[],
|
||||
workspaceDirs: string[],
|
||||
): string => {
|
||||
const currentFilepathComment = addCommentMarks(
|
||||
getCurrentFilepath(helper),
|
||||
getLastNUriRelativePathParts(workspaceDirs, helper.filepath, 2),
|
||||
helper,
|
||||
);
|
||||
|
||||
|
|
@ -77,11 +76,11 @@ export const formatSnippets = (
|
|||
.map((snippet) => {
|
||||
switch (snippet.type) {
|
||||
case AutocompleteSnippetType.Code:
|
||||
return formatCodeSnippet(snippet);
|
||||
return formatCodeSnippet(snippet, workspaceDirs);
|
||||
case AutocompleteSnippetType.Diff:
|
||||
return formatDiffSnippet(snippet);
|
||||
case AutocompleteSnippetType.Clipboard:
|
||||
return formatClipboardSnippet(snippet);
|
||||
return formatClipboardSnippet(snippet, workspaceDirs);
|
||||
}
|
||||
})
|
||||
.map((item) => {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import Handlebars from "handlebars";
|
||||
|
||||
import { CompletionOptions } from "../..";
|
||||
import { getBasename } from "../../util";
|
||||
import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
||||
|
|
@ -11,6 +10,7 @@ import {
|
|||
getTemplateForModel,
|
||||
} from "./AutocompleteTemplate";
|
||||
import { getSnippets } from "./filtering";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
import { formatSnippets } from "./formatting";
|
||||
import { getStopTokens } from "./getStopTokens";
|
||||
|
||||
|
|
@ -33,7 +33,7 @@ function renderStringTemplate(
|
|||
filepath: string,
|
||||
reponame: string,
|
||||
) {
|
||||
const filename = getBasename(filepath);
|
||||
const filename = getUriPathBasename(filepath);
|
||||
const compiledTemplate = Handlebars.compile(template);
|
||||
|
||||
return compiledTemplate({
|
||||
|
|
@ -66,7 +66,7 @@ export function renderPrompt({
|
|||
suffix = "\n";
|
||||
}
|
||||
|
||||
const reponame = getBasename(workspaceDirs[0] ?? "myproject");
|
||||
const reponame = getUriPathBasename(workspaceDirs[0] ?? "myproject");
|
||||
|
||||
const { template, compilePrefixSuffix, completionOptions } =
|
||||
getTemplate(helper);
|
||||
|
|
@ -82,9 +82,10 @@ export function renderPrompt({
|
|||
helper.filepath,
|
||||
reponame,
|
||||
snippets,
|
||||
helper.workspaceUris,
|
||||
);
|
||||
} else {
|
||||
const formattedSnippets = formatSnippets(helper, snippets);
|
||||
const formattedSnippets = formatSnippets(helper, snippets, workspaceDirs);
|
||||
prefix = [formattedSnippets, prefix].join("\n");
|
||||
}
|
||||
|
||||
|
|
@ -106,6 +107,7 @@ export function renderPrompt({
|
|||
reponame,
|
||||
helper.lang.name,
|
||||
snippets,
|
||||
helper.workspaceUris,
|
||||
);
|
||||
|
||||
const stopTokens = getStopTokens(
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { logDevData } from "../../util/devdata";
|
||||
import { COUNT_COMPLETION_REJECTED_AFTER } from "../../util/parameters";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import { getUriFileExtension } from "../../util/uri";
|
||||
|
||||
import { AutocompleteOutcome } from "./types";
|
||||
|
||||
|
|
@ -105,7 +106,7 @@ export class AutocompleteLoggingService {
|
|||
completionId: restOfOutcome.completionId,
|
||||
completionOptions: restOfOutcome.completionOptions,
|
||||
debounceDelay: restOfOutcome.debounceDelay,
|
||||
fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0],
|
||||
fileExtension: getUriFileExtension(restOfOutcome.filepath),
|
||||
maxPromptTokens: restOfOutcome.maxPromptTokens,
|
||||
modelName: restOfOutcome.modelName,
|
||||
modelProvider: restOfOutcome.modelProvider,
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ import { AutocompleteInput } from "./types";
|
|||
export class HelperVars {
|
||||
lang: AutocompleteLanguageInfo;
|
||||
treePath: AstPath | undefined;
|
||||
workspaceUris: string[] = [];
|
||||
|
||||
private _fileContents: string | undefined;
|
||||
private _fileLines: string[] | undefined;
|
||||
|
|
@ -43,6 +44,8 @@ export class HelperVars {
|
|||
return;
|
||||
}
|
||||
|
||||
this.workspaceUris = await this.ide.getWorkspaceDirs();
|
||||
|
||||
this._fileContents =
|
||||
this.input.manuallyPassFileContents ??
|
||||
(await this.ide.readFile(this.filepath));
|
||||
|
|
|
|||
|
|
@ -1,15 +1,18 @@
|
|||
import * as fs from "fs/promises";
|
||||
import * as path from "path";
|
||||
|
||||
import ignore from "ignore";
|
||||
|
||||
import { IDE, SlashCommand } from "../..";
|
||||
import type { FileType, IDE, SlashCommand } from "../..";
|
||||
import {
|
||||
defaultIgnoreDir,
|
||||
defaultIgnoreFile,
|
||||
getGlobalContinueIgArray,
|
||||
gitIgArrayFromFile,
|
||||
} from "../../indexing/ignore";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
import {
|
||||
findUriInDirs,
|
||||
getUriPathBasename,
|
||||
joinPathsToUri,
|
||||
} from "../../util/uri";
|
||||
|
||||
const LANGUAGE_DEP_MGMT_FILENAMES = [
|
||||
"package.json", // JavaScript (Node.js)
|
||||
|
|
@ -55,30 +58,43 @@ const OnboardSlashCommand: SlashCommand = {
|
|||
};
|
||||
|
||||
async function getEntriesFilteredByIgnore(dir: string, ide: IDE) {
|
||||
const entries = await fs.readdir(dir, { withFileTypes: true });
|
||||
const ig = ignore()
|
||||
.add(defaultIgnoreDir)
|
||||
.add(defaultIgnoreFile)
|
||||
.add(getGlobalContinueIgArray());
|
||||
const entries = await ide.listDir(dir);
|
||||
|
||||
let ig = ignore().add(defaultIgnoreDir).add(defaultIgnoreFile);
|
||||
const ignoreUri = joinPathsToUri(dir, ".gitignore");
|
||||
const fileExists = await ide.fileExists(ignoreUri);
|
||||
|
||||
const gitIgnorePath = path.join(dir, ".gitignore");
|
||||
|
||||
const hasIgnoreFile = await fs
|
||||
.access(gitIgnorePath)
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
|
||||
if (hasIgnoreFile) {
|
||||
const gitIgnore = await ide.readFile(gitIgnorePath);
|
||||
if (fileExists) {
|
||||
const gitIgnore = await ide.readFile(ignoreUri);
|
||||
const igPatterns = gitIgArrayFromFile(gitIgnore);
|
||||
|
||||
ig = ig.add(igPatterns);
|
||||
ig.add(igPatterns);
|
||||
}
|
||||
|
||||
const filteredEntries = entries.filter((entry) => {
|
||||
const name = entry.isDirectory() ? `${entry.name}/` : entry.name;
|
||||
return !ig.ignores(name);
|
||||
});
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
|
||||
return filteredEntries;
|
||||
const withRelativePaths = entries
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry[1] === (1 as FileType.File) ||
|
||||
entry[1] === (2 as FileType.Directory),
|
||||
)
|
||||
.map((entry) => {
|
||||
const { relativePathOrBasename } = findUriInDirs(entry[0], workspaceDirs);
|
||||
return {
|
||||
uri: entry[0],
|
||||
type: entry[1],
|
||||
basename: getUriPathBasename(entry[0]),
|
||||
relativePath:
|
||||
relativePathOrBasename +
|
||||
(entry[1] === (2 as FileType.Directory) ? "/" : ""),
|
||||
};
|
||||
});
|
||||
|
||||
return withRelativePaths.filter((entry) => !ig.ignores(entry.relativePath));
|
||||
}
|
||||
|
||||
async function gatherProjectContext(
|
||||
|
|
@ -86,7 +102,6 @@ async function gatherProjectContext(
|
|||
ide: IDE,
|
||||
): Promise<string> {
|
||||
let context = "";
|
||||
|
||||
async function exploreDirectory(dir: string, currentDepth: number = 0) {
|
||||
if (currentDepth > MAX_EXPLORE_DEPTH) {
|
||||
return;
|
||||
|
|
@ -95,19 +110,16 @@ async function gatherProjectContext(
|
|||
const entries = await getEntriesFilteredByIgnore(dir, ide);
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = path.join(dir, entry.name);
|
||||
const relativePath = path.relative(workspaceDir, fullPath);
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
context += `\nFolder: ${relativePath}\n`;
|
||||
await exploreDirectory(fullPath, currentDepth + 1);
|
||||
if (entry.type === (2 as FileType.Directory)) {
|
||||
context += `\nFolder: ${entry.relativePath}\n`;
|
||||
await exploreDirectory(entry.uri, currentDepth + 1);
|
||||
} else {
|
||||
if (entry.name.toLowerCase() === "readme.md") {
|
||||
const content = await fs.readFile(fullPath, "utf-8");
|
||||
context += `README for ${relativePath}:\n${content}\n\n`;
|
||||
} else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.name)) {
|
||||
const content = await fs.readFile(fullPath, "utf-8");
|
||||
context += `${entry.name} for ${relativePath}:\n${content}\n\n`;
|
||||
if (entry.basename.toLowerCase() === "readme.md") {
|
||||
const content = await ide.readFile(entry.uri);
|
||||
context += `README for ${entry.relativePath}:\n${content}\n\n`;
|
||||
} else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.basename)) {
|
||||
const content = await ide.readFile(entry.uri);
|
||||
context += `${entry.basename} for ${entry.relativePath}:\n${content}\n\n`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
import * as fs from "node:fs";
|
||||
import fs from "fs";
|
||||
import { homedir } from "node:os";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import path from "path";
|
||||
|
||||
import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js";
|
||||
import { SlashCommand } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { getContinueGlobalPath } from "../../util/paths.js";
|
||||
|
||||
// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
|
||||
function getOffsetDatetime(date: Date): Date {
|
||||
|
|
@ -62,10 +64,7 @@ const ShareSlashCommand: SlashCommand = {
|
|||
}\n\n${msgText}`;
|
||||
}
|
||||
|
||||
let outputDir: string = params?.outputDir;
|
||||
if (!outputDir) {
|
||||
outputDir = await ide.getContinueDir();
|
||||
}
|
||||
let outputDir: string = params?.outputDir ?? getContinueGlobalPath();
|
||||
|
||||
if (outputDir.startsWith("~")) {
|
||||
outputDir = outputDir.replace(/^~/, homedir);
|
||||
|
|
@ -81,7 +80,7 @@ const ShareSlashCommand: SlashCommand = {
|
|||
// folders are included. We default to using the first item in the list, if
|
||||
// it exists.
|
||||
const workspaceDirectory = workspaceDirs?.[0] || "";
|
||||
outputDir = outputDir.replace(/^./, workspaceDirectory);
|
||||
outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory));
|
||||
}
|
||||
|
||||
if (!fs.existsSync(outputDir)) {
|
||||
|
|
@ -91,8 +90,9 @@ const ShareSlashCommand: SlashCommand = {
|
|||
const dtString = asBasicISOString(getOffsetDatetime(now));
|
||||
const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming?
|
||||
|
||||
await ide.writeFile(outPath, content);
|
||||
await ide.openFile(outPath);
|
||||
const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^
|
||||
await ide.writeFile(fileUrl, content);
|
||||
await ide.openFile(fileUrl);
|
||||
|
||||
yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`;
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,7 +1,35 @@
|
|||
import { ContextItemWithId, RangeInFileWithContents } from "../";
|
||||
import { findUriInDirs, getUriPathBasename } from "../util/uri";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
export function rifWithContentsToContextItem(
|
||||
rif: RangeInFileWithContents,
|
||||
): ContextItemWithId {
|
||||
const basename = getUriPathBasename(rif.filepath);
|
||||
const { relativePathOrBasename, foundInDir, uri } = findUriInDirs(
|
||||
rif.filepath,
|
||||
window.workspacePaths ?? [],
|
||||
);
|
||||
const rangeStr = `(${rif.range.start.line + 1}-${rif.range.end.line + 1})`;
|
||||
|
||||
return {
|
||||
content: rif.contents,
|
||||
name: `${basename} ${rangeStr}`,
|
||||
description: `${relativePathOrBasename} ${rangeStr}`, // This is passed to the LLM - do not pass full URI
|
||||
id: {
|
||||
providerTitle: "code",
|
||||
itemId: uuidv4(),
|
||||
},
|
||||
uri: {
|
||||
type: "file",
|
||||
value: rif.filepath,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function ctxItemToRifWithContents(
|
||||
item: ContextItemWithId,
|
||||
linesOffByOne = false,
|
||||
): RangeInFileWithContents {
|
||||
let startLine = 0;
|
||||
let endLine = 0;
|
||||
|
|
@ -10,8 +38,8 @@ export function ctxItemToRifWithContents(
|
|||
|
||||
if (nameSplit.length > 1) {
|
||||
const lines = nameSplit[1].split(")")[0].split("-");
|
||||
startLine = Number.parseInt(lines[0], 10);
|
||||
endLine = Number.parseInt(lines[1], 10);
|
||||
startLine = Number.parseInt(lines[0], 10) - (linesOffByOne ? 1 : 0);
|
||||
endLine = Number.parseInt(lines[1], 10) - (linesOffByOne ? 1 : 0);
|
||||
}
|
||||
|
||||
const rif: RangeInFileWithContents = {
|
||||
|
|
|
|||
|
|
@ -1,14 +1,13 @@
|
|||
import { IDE } from "..";
|
||||
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
export const SYSTEM_PROMPT_DOT_FILE = ".continuerules";
|
||||
|
||||
export async function getSystemPromptDotFile(ide: IDE): Promise<string | null> {
|
||||
const dirs = await ide.getWorkspaceDirs();
|
||||
|
||||
let prompts: string[] = [];
|
||||
const pathSep = await ide.pathSep();
|
||||
for (const dir of dirs) {
|
||||
const dotFile = `${dir}${pathSep}${SYSTEM_PROMPT_DOT_FILE}`;
|
||||
const dotFile = joinPathsToUri(dir, SYSTEM_PROMPT_DOT_FILE);
|
||||
if (await ide.fileExists(dotFile)) {
|
||||
try {
|
||||
const content = await ide.readFile(dotFile);
|
||||
|
|
|
|||
|
|
@ -59,7 +59,6 @@ import {
|
|||
getConfigTsPath,
|
||||
getContinueDotEnv,
|
||||
getEsbuildBinaryPath,
|
||||
readAllGlobalPromptFiles,
|
||||
} from "../util/paths";
|
||||
|
||||
import {
|
||||
|
|
@ -69,12 +68,9 @@ import {
|
|||
defaultSlashCommandsVscode,
|
||||
} from "./default";
|
||||
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
|
||||
import {
|
||||
DEFAULT_PROMPTS_FOLDER,
|
||||
getPromptFiles,
|
||||
slashCommandFromPromptFile,
|
||||
} from "./promptFile.js";
|
||||
import { ConfigValidationError, validateConfig } from "./validation.js";
|
||||
import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
|
||||
import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
|
||||
|
||||
export interface ConfigResult<T> {
|
||||
config: T | undefined;
|
||||
|
|
@ -184,8 +180,8 @@ function loadSerializedConfig(
|
|||
async function serializedToIntermediateConfig(
|
||||
initial: SerializedContinueConfig,
|
||||
ide: IDE,
|
||||
loadPromptFiles: boolean = true,
|
||||
): Promise<Config> {
|
||||
// DEPRECATED - load custom slash commands
|
||||
const slashCommands: SlashCommand[] = [];
|
||||
for (const command of initial.slashCommands || []) {
|
||||
const newCommand = slashCommandFromDescription(command);
|
||||
|
|
@ -197,33 +193,18 @@ async function serializedToIntermediateConfig(
|
|||
slashCommands.push(slashFromCustomCommand(command));
|
||||
}
|
||||
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
const promptFolder = initial.experimental?.promptPath;
|
||||
// DEPRECATED - load slash commands from v1 prompt files
|
||||
// NOTE: still checking the v1 default .prompts folder for slash commands
|
||||
const promptFiles = await getAllPromptFiles(
|
||||
ide,
|
||||
initial.experimental?.promptPath,
|
||||
true,
|
||||
);
|
||||
|
||||
if (loadPromptFiles) {
|
||||
// v1 prompt files
|
||||
let promptFiles: { path: string; content: string }[] = [];
|
||||
promptFiles = (
|
||||
await Promise.all(
|
||||
workspaceDirs.map((dir) =>
|
||||
getPromptFiles(
|
||||
ide,
|
||||
path.join(dir, promptFolder ?? DEFAULT_PROMPTS_FOLDER),
|
||||
),
|
||||
),
|
||||
)
|
||||
)
|
||||
.flat()
|
||||
.filter(({ path }) => path.endsWith(".prompt"));
|
||||
|
||||
// Also read from ~/.continue/.prompts
|
||||
promptFiles.push(...readAllGlobalPromptFiles());
|
||||
|
||||
for (const file of promptFiles) {
|
||||
const slashCommand = slashCommandFromPromptFile(file.path, file.content);
|
||||
if (slashCommand) {
|
||||
slashCommands.push(slashCommand);
|
||||
}
|
||||
for (const file of promptFiles) {
|
||||
const slashCommand = slashCommandFromPromptFileV1(file.path, file.content);
|
||||
if (slashCommand) {
|
||||
slashCommands.push(slashCommand);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -865,6 +846,5 @@ export {
|
|||
finalToBrowserConfig,
|
||||
intermediateToFinalConfig,
|
||||
loadFullConfigNode,
|
||||
serializedToIntermediateConfig,
|
||||
type BrowserSerializedContinueConfig,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { FREE_TRIAL_MODELS } from "./default";
|
|||
|
||||
export const TRIAL_FIM_MODEL = "codestral-latest";
|
||||
export const ONBOARDING_LOCAL_MODEL_TITLE = "Ollama";
|
||||
export const LOCAL_ONBOARDING_FIM_MODEL = "qwen2.5-coder:1.5b";
|
||||
export const LOCAL_ONBOARDING_FIM_MODEL = "qwen2.5-coder:1.5b-base";
|
||||
export const LOCAL_ONBOARDING_CHAT_MODEL = "llama3.1:8b";
|
||||
export const LOCAL_ONBOARDING_CHAT_TITLE = "Llama 3.1 8B";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,285 +0,0 @@
|
|||
import path from "path";
|
||||
|
||||
import Handlebars from "handlebars";
|
||||
import * as YAML from "yaml";
|
||||
|
||||
import { walkDir } from "../indexing/walkDir";
|
||||
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
|
||||
import { getBasename } from "../util/index";
|
||||
import { renderChatMessage } from "../util/messageContent";
|
||||
|
||||
import type {
|
||||
ChatMessage,
|
||||
ContextItem,
|
||||
ContinueSDK,
|
||||
IContextProvider,
|
||||
IDE,
|
||||
SlashCommand,
|
||||
} from "..";
|
||||
|
||||
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
|
||||
|
||||
export async function getPromptFiles(
|
||||
ide: IDE,
|
||||
dir: string,
|
||||
): Promise<{ path: string; content: string }[]> {
|
||||
try {
|
||||
const exists = await ide.fileExists(dir);
|
||||
|
||||
if (!exists) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const paths = await walkDir(dir, ide, { ignoreFiles: [] });
|
||||
const results = paths.map(async (path) => {
|
||||
const content = await ide.readFile(path);
|
||||
return { path, content };
|
||||
});
|
||||
return Promise.all(results);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
|
||||
# It is used to define and reuse prompts within Continue
|
||||
# Continue will automatically create a slash command for each prompt in the .prompts folder
|
||||
# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files
|
||||
temperature: 0.0
|
||||
---
|
||||
{{{ diff }}}
|
||||
|
||||
Give me feedback on the above changes. For each file, you should output a markdown section including the following:
|
||||
- If you found any problems, an h3 like "❌ <filename>"
|
||||
- If you didn't find any problems, an h3 like "✅ <filename>"
|
||||
- If you found any problems, add below a bullet point description of what you found, including a minimal code snippet explaining how to fix it
|
||||
- If you didn't find any problems, you don't need to add anything else
|
||||
|
||||
Here is an example. The example is surrounded in backticks, but your response should not be:
|
||||
|
||||
\`\`\`
|
||||
### ✅ <Filename1>
|
||||
|
||||
### ❌ <Filename2>
|
||||
|
||||
<Description>
|
||||
\`\`\`
|
||||
|
||||
You should look primarily for the following types of issues, and only mention other problems if they are highly pressing.
|
||||
|
||||
- console.logs that have been left after debugging
|
||||
- repeated code
|
||||
- algorithmic errors that could fail under edge cases
|
||||
- something that could be refactored
|
||||
|
||||
Make sure to review ALL files that were changed, do not skip any.
|
||||
`;
|
||||
|
||||
export async function createNewPromptFile(
|
||||
ide: IDE,
|
||||
promptPath: string | undefined,
|
||||
): Promise<void> {
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
if (workspaceDirs.length === 0) {
|
||||
throw new Error(
|
||||
"No workspace directories found. Make sure you've opened a folder in your IDE.",
|
||||
);
|
||||
}
|
||||
const promptFilePath = path.join(
|
||||
workspaceDirs[0],
|
||||
promptPath ?? DEFAULT_PROMPTS_FOLDER,
|
||||
"new-prompt-file.prompt",
|
||||
);
|
||||
|
||||
await ide.writeFile(promptFilePath, DEFAULT_PROMPT_FILE);
|
||||
await ide.openFile(promptFilePath);
|
||||
}
|
||||
|
||||
export function slashCommandFromPromptFile(
|
||||
path: string,
|
||||
content: string,
|
||||
): SlashCommand | null {
|
||||
const { name, description, systemMessage, prompt, version } = parsePromptFile(
|
||||
path,
|
||||
content,
|
||||
);
|
||||
|
||||
if (version !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
run: async function* (context) {
|
||||
const originalSystemMessage = context.llm.systemMessage;
|
||||
context.llm.systemMessage = systemMessage;
|
||||
|
||||
const userInput = extractUserInput(context.input, name);
|
||||
const renderedPrompt = await renderPrompt(prompt, context, userInput);
|
||||
const messages = updateChatHistory(
|
||||
context.history,
|
||||
name,
|
||||
renderedPrompt,
|
||||
systemMessage,
|
||||
);
|
||||
|
||||
for await (const chunk of context.llm.streamChat(
|
||||
messages,
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
|
||||
context.llm.systemMessage = originalSystemMessage;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function parsePromptFile(path: string, content: string) {
|
||||
let [preambleRaw, prompt] = content.split("\n---\n");
|
||||
if (prompt === undefined) {
|
||||
prompt = preambleRaw;
|
||||
preambleRaw = "";
|
||||
}
|
||||
|
||||
const preamble = YAML.parse(preambleRaw) ?? {};
|
||||
const name = preamble.name ?? getBasename(path).split(".prompt")[0];
|
||||
const description = preamble.description ?? name;
|
||||
const version = preamble.version ?? 2;
|
||||
|
||||
let systemMessage: string | undefined = undefined;
|
||||
if (prompt.includes("<system>")) {
|
||||
systemMessage = prompt.split("<system>")[1].split("</system>")[0].trim();
|
||||
prompt = prompt.split("</system>")[1].trim();
|
||||
}
|
||||
|
||||
return { name, description, systemMessage, prompt, version };
|
||||
}
|
||||
|
||||
function extractUserInput(input: string, commandName: string): string {
|
||||
if (input.startsWith(`/${commandName}`)) {
|
||||
return input.slice(commandName.length + 1).trimStart();
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
async function renderPrompt(
|
||||
prompt: string,
|
||||
context: ContinueSDK,
|
||||
userInput: string,
|
||||
) {
|
||||
const helpers = getContextProviderHelpers(context);
|
||||
|
||||
// A few context providers that don't need to be in config.json to work in .prompt files
|
||||
const diff = await context.ide.getDiff(true);
|
||||
const currentFile = await context.ide.getCurrentFile();
|
||||
const inputData: Record<string, string> = {
|
||||
diff: diff.join("\n"),
|
||||
input: userInput,
|
||||
};
|
||||
if (currentFile) {
|
||||
inputData.currentFile = currentFile.path;
|
||||
}
|
||||
|
||||
return renderTemplatedString(
|
||||
prompt,
|
||||
context.ide.readFile.bind(context.ide),
|
||||
inputData,
|
||||
helpers,
|
||||
);
|
||||
}
|
||||
|
||||
function getContextProviderHelpers(
|
||||
context: ContinueSDK,
|
||||
): Array<[string, Handlebars.HelperDelegate]> | undefined {
|
||||
return context.config.contextProviders?.map((provider: IContextProvider) => [
|
||||
provider.description.title,
|
||||
async (helperContext: any) => {
|
||||
const items = await provider.getContextItems(helperContext, {
|
||||
config: context.config,
|
||||
embeddingsProvider: context.config.embeddingsProvider,
|
||||
fetch: context.fetch,
|
||||
fullInput: context.input,
|
||||
ide: context.ide,
|
||||
llm: context.llm,
|
||||
reranker: context.config.reranker,
|
||||
selectedCode: context.selectedCode,
|
||||
});
|
||||
|
||||
items.forEach((item) =>
|
||||
context.addContextItem(createContextItem(item, provider)),
|
||||
);
|
||||
|
||||
return items.map((item) => item.content).join("\n\n");
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function createContextItem(item: ContextItem, provider: IContextProvider) {
|
||||
return {
|
||||
...item,
|
||||
id: {
|
||||
itemId: item.description,
|
||||
providerTitle: provider.description.title,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function updateChatHistory(
|
||||
history: ChatMessage[],
|
||||
commandName: string,
|
||||
renderedPrompt: string,
|
||||
systemMessage?: string,
|
||||
) {
|
||||
const messages = [...history];
|
||||
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const message = messages[i];
|
||||
const { role, content } = message;
|
||||
if (role !== "user") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Array.isArray(content)) {
|
||||
if (content.some((part) => part.text?.startsWith(`/${commandName}`))) {
|
||||
messages[i] = updateArrayContent(
|
||||
messages[i],
|
||||
commandName,
|
||||
renderedPrompt,
|
||||
);
|
||||
break;
|
||||
}
|
||||
} else if (
|
||||
typeof content === "string" &&
|
||||
content.startsWith(`/${commandName}`)
|
||||
) {
|
||||
messages[i] = { ...message, content: renderedPrompt };
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (systemMessage) {
|
||||
messages[0]?.role === "system"
|
||||
? (messages[0].content = systemMessage)
|
||||
: messages.unshift({ role: "system", content: systemMessage });
|
||||
}
|
||||
|
||||
return messages;
|
||||
}
|
||||
|
||||
function updateArrayContent(
|
||||
message: any,
|
||||
commandName: string,
|
||||
renderedPrompt: string,
|
||||
) {
|
||||
return {
|
||||
...message,
|
||||
content: message.content.map((part: any) =>
|
||||
part.text?.startsWith(`/${commandName}`)
|
||||
? { ...part, text: renderedPrompt }
|
||||
: part,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
|
@ -607,8 +607,6 @@ declare global {
|
|||
|
||||
getAvailableThreads(): Promise<Thread[]>;
|
||||
|
||||
listFolders(): Promise<string[]>;
|
||||
|
||||
getWorkspaceDirs(): Promise<string[]>;
|
||||
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
|
||||
|
|
@ -618,9 +616,6 @@ declare global {
|
|||
writeFile(path: string, contents: string): Promise<void>;
|
||||
|
||||
showVirtualFile(title: string, contents: string): Promise<void>;
|
||||
|
||||
getContinueDir(): Promise<string>;
|
||||
|
||||
openFile(path: string): Promise<void>;
|
||||
|
||||
openUrl(url: string): Promise<void>;
|
||||
|
|
@ -638,13 +633,6 @@ declare global {
|
|||
startLine: number,
|
||||
endLine: number,
|
||||
): Promise<void>;
|
||||
|
||||
showDiff(
|
||||
filepath: string,
|
||||
newContents: string,
|
||||
stepIndex: number,
|
||||
): Promise<void>;
|
||||
|
||||
getOpenFiles(): Promise<string[]>;
|
||||
|
||||
getCurrentFile(): Promise<
|
||||
|
|
@ -689,8 +677,6 @@ declare global {
|
|||
|
||||
// Callbacks
|
||||
onDidChangeActiveTextEditor(callback: (filepath: string) => void): void;
|
||||
|
||||
pathSep(): Promise<string>;
|
||||
}
|
||||
|
||||
// Slash Commands
|
||||
|
|
|
|||
|
|
@ -32,14 +32,11 @@ import {
|
|||
readAllGlobalPromptFiles,
|
||||
} from "../../util/paths";
|
||||
import { getSystemPromptDotFile } from "../getSystemPromptDotFile";
|
||||
import {
|
||||
DEFAULT_PROMPTS_FOLDER,
|
||||
getPromptFiles,
|
||||
slashCommandFromPromptFile,
|
||||
} from "../promptFile.js";
|
||||
import { ConfigValidationError } from "../validation.js";
|
||||
|
||||
import { llmsFromModelConfig } from "./models";
|
||||
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
|
||||
import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
|
||||
|
||||
export interface ConfigResult<T> {
|
||||
config: T | undefined;
|
||||
|
|
@ -102,25 +99,11 @@ async function slashCommandsFromV1PromptFiles(
|
|||
ide: IDE,
|
||||
): Promise<SlashCommand[]> {
|
||||
const slashCommands: SlashCommand[] = [];
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
|
||||
// v1 prompt files
|
||||
let promptFiles: { path: string; content: string }[] = [];
|
||||
promptFiles = (
|
||||
await Promise.all(
|
||||
workspaceDirs.map((dir) =>
|
||||
getPromptFiles(ide, path.join(dir, DEFAULT_PROMPTS_FOLDER)),
|
||||
),
|
||||
)
|
||||
)
|
||||
.flat()
|
||||
.filter(({ path }) => path.endsWith(".prompt"));
|
||||
|
||||
// Also read from ~/.continue/.prompts
|
||||
promptFiles.push(...readAllGlobalPromptFiles());
|
||||
const promptFiles = await getAllPromptFiles(ide, undefined, true);
|
||||
|
||||
for (const file of promptFiles) {
|
||||
const slashCommand = slashCommandFromPromptFile(file.path, file.content);
|
||||
const slashCommand = slashCommandFromPromptFileV1(file.path, file.content);
|
||||
if (slashCommand) {
|
||||
slashCommands.push(slashCommand);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ import {
|
|||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { getBasename } from "../../util/index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
const HIGHLIGHTS_TOKEN_BUDGET = 2000;
|
||||
|
|
@ -26,16 +25,16 @@ class CodeHighlightsContextProvider extends BaseContextProvider {
|
|||
// );
|
||||
const ide = extras.ide;
|
||||
const openFiles = await ide.getOpenFiles();
|
||||
const allFiles: { name: string; absPath: string; content: string }[] =
|
||||
await Promise.all(
|
||||
openFiles.map(async (filepath: string) => {
|
||||
return {
|
||||
name: getBasename(filepath),
|
||||
absPath: filepath,
|
||||
content: `${await ide.readFile(filepath)}`,
|
||||
};
|
||||
}),
|
||||
);
|
||||
// const allFiles: { name: string; absPath: string; content: string }[] =
|
||||
// await Promise.all(
|
||||
// openFiles.map(async (filepath: string) => {
|
||||
// return {
|
||||
// name: getBasename(filepath),
|
||||
// absPath: filepath,
|
||||
// content: `${await ide.readFile(filepath)}`,
|
||||
// };
|
||||
// }),
|
||||
// );
|
||||
// const contextSizer = {
|
||||
// fits(content: string): boolean {
|
||||
// return countTokens(content, "") < HIGHLIGHTS_TOKEN_BUDGET;
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ import {
|
|||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { getBasename } from "../../util/index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
class CodeOutlineContextProvider extends BaseContextProvider {
|
||||
|
|
@ -21,16 +20,16 @@ class CodeOutlineContextProvider extends BaseContextProvider {
|
|||
): Promise<ContextItem[]> {
|
||||
const ide = extras.ide;
|
||||
const openFiles = await ide.getOpenFiles();
|
||||
const allFiles: { name: string; absPath: string; content: string }[] =
|
||||
await Promise.all(
|
||||
openFiles.map(async (filepath: string) => {
|
||||
return {
|
||||
name: getBasename(filepath),
|
||||
absPath: filepath,
|
||||
content: `${await ide.readFile(filepath)}`,
|
||||
};
|
||||
}),
|
||||
);
|
||||
// const allFiles: { name: string; absPath: string; content: string }[] =
|
||||
// await Promise.all(
|
||||
// openFiles.map(async (filepath: string) => {
|
||||
// return {
|
||||
// name: getBasename(filepath),
|
||||
// absPath: filepath,
|
||||
// content: `${await ide.readFile(filepath)}`,
|
||||
// };
|
||||
// }),
|
||||
// );
|
||||
// const outlines = await getOutlines(
|
||||
// allFiles
|
||||
// .filter((file) => file.content.length > 0)
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import {
|
|||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../";
|
||||
import { getBasename } from "../../util/";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
|
||||
class CurrentFileContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
|
|
@ -19,12 +19,11 @@ class CurrentFileContextProvider extends BaseContextProvider {
|
|||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const ide = extras.ide;
|
||||
const currentFile = await ide.getCurrentFile();
|
||||
const currentFile = await extras.ide.getCurrentFile();
|
||||
if (!currentFile) {
|
||||
return [];
|
||||
}
|
||||
const baseName = getBasename(currentFile.path);
|
||||
const baseName = getUriPathBasename(currentFile.path);
|
||||
return [
|
||||
{
|
||||
description: currentFile.path,
|
||||
|
|
|
|||
|
|
@ -6,12 +6,11 @@ import {
|
|||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../";
|
||||
import { walkDir } from "../../indexing/walkDir";
|
||||
import { walkDirs } from "../../indexing/walkDir";
|
||||
import {
|
||||
getBasename,
|
||||
getUniqueFilePath,
|
||||
groupByLastNPathParts,
|
||||
} from "../../util/";
|
||||
getUriPathBasename,
|
||||
getShortestUniqueRelativeUriPaths,
|
||||
} from "../../util/uri";
|
||||
|
||||
const MAX_SUBMENU_ITEMS = 10_000;
|
||||
|
||||
|
|
@ -47,19 +46,18 @@ class FileContextProvider extends BaseContextProvider {
|
|||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const workspaceDirs = await args.ide.getWorkspaceDirs();
|
||||
const results = await Promise.all(
|
||||
workspaceDirs.map((dir) => {
|
||||
return walkDir(dir, args.ide);
|
||||
}),
|
||||
);
|
||||
const results = await walkDirs(args.ide, undefined, workspaceDirs);
|
||||
const files = results.flat().slice(-MAX_SUBMENU_ITEMS);
|
||||
const fileGroups = groupByLastNPathParts(files, 2);
|
||||
const withUniquePaths = getShortestUniqueRelativeUriPaths(
|
||||
files,
|
||||
workspaceDirs,
|
||||
);
|
||||
|
||||
return files.map((file) => {
|
||||
return withUniquePaths.map((file) => {
|
||||
return {
|
||||
id: file,
|
||||
title: getBasename(file),
|
||||
description: getUniqueFilePath(file, fileGroups),
|
||||
id: file.uri,
|
||||
title: getUriPathBasename(file.uri),
|
||||
description: file.uniquePath,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import {
|
|||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { walkDir } from "../../indexing/walkDir.js";
|
||||
import { splitPath } from "../../util/index.js";
|
||||
import { findUriInDirs, getUriPathBasename } from "../../util/uri.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
interface Directory {
|
||||
|
|
@ -44,16 +44,19 @@ class FileTreeContextProvider extends BaseContextProvider {
|
|||
const trees = [];
|
||||
|
||||
for (const workspaceDir of workspaceDirs) {
|
||||
const contents = await walkDir(workspaceDir, extras.ide);
|
||||
|
||||
const subDirTree: Directory = {
|
||||
name: splitPath(workspaceDir).pop() ?? "",
|
||||
name: getUriPathBasename(workspaceDir),
|
||||
files: [],
|
||||
directories: [],
|
||||
};
|
||||
|
||||
for (const file of contents) {
|
||||
const parts = splitPath(file, workspaceDir);
|
||||
const uris = await walkDir(workspaceDir, extras.ide);
|
||||
const relativePaths = uris.map(
|
||||
(uri) => findUriInDirs(uri, [workspaceDir]).relativePathOrBasename,
|
||||
);
|
||||
|
||||
for (const path of relativePaths) {
|
||||
const parts = path.split("/");
|
||||
|
||||
let currentTree = subDirTree;
|
||||
for (const part of parts.slice(0, -1)) {
|
||||
|
|
|
|||
|
|
@ -5,12 +5,13 @@ import {
|
|||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../index.js";
|
||||
import { walkDirs } from "../../indexing/walkDir.js";
|
||||
import {
|
||||
getBasename,
|
||||
groupByLastNPathParts,
|
||||
getUniqueFilePath,
|
||||
} from "../../util/index.js";
|
||||
getShortestUniqueRelativeUriPaths,
|
||||
getUriPathBasename,
|
||||
} from "../../util/uri.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
import { retrieveContextItemsFromEmbeddings } from "../retrieval/retrieval.js";
|
||||
|
||||
class FolderContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
|
|
@ -25,22 +26,29 @@ class FolderContextProvider extends BaseContextProvider {
|
|||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const { retrieveContextItemsFromEmbeddings } = await import(
|
||||
"../retrieval/retrieval.js"
|
||||
);
|
||||
return retrieveContextItemsFromEmbeddings(extras, this.options, query);
|
||||
}
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const folders = await args.ide.listFolders();
|
||||
const folderGroups = groupByLastNPathParts(folders, 2);
|
||||
const workspaceDirs = await args.ide.getWorkspaceDirs();
|
||||
const folders = await walkDirs(
|
||||
args.ide,
|
||||
{
|
||||
onlyDirs: true,
|
||||
},
|
||||
workspaceDirs,
|
||||
);
|
||||
const withUniquePaths = getShortestUniqueRelativeUriPaths(
|
||||
folders,
|
||||
workspaceDirs,
|
||||
);
|
||||
|
||||
return folders.map((folder) => {
|
||||
return withUniquePaths.map((folder) => {
|
||||
return {
|
||||
id: folder,
|
||||
title: getBasename(folder),
|
||||
description: getUniqueFilePath(folder, folderGroups),
|
||||
id: folder.uri,
|
||||
title: getUriPathBasename(folder.uri),
|
||||
description: folder.uniquePath,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,188 +1,209 @@
|
|||
import { execSync } from "child_process";
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
import { execSync } from "child_process";
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
|
||||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
|
||||
class GreptileContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "greptile",
|
||||
displayTitle: "Greptile",
|
||||
description: "Insert query to Greptile",
|
||||
type: "query",
|
||||
class GreptileContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "greptile",
|
||||
displayTitle: "Greptile",
|
||||
description: "Insert query to Greptile",
|
||||
type: "query",
|
||||
};
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const greptileToken = this.getGreptileToken();
|
||||
if (!greptileToken) {
|
||||
throw new Error("Greptile token not found.");
|
||||
}
|
||||
|
||||
const githubToken = this.getGithubToken();
|
||||
if (!githubToken) {
|
||||
throw new Error("GitHub token not found.");
|
||||
}
|
||||
|
||||
let absPath = await this.getWorkspaceDir(extras);
|
||||
if (!absPath) {
|
||||
throw new Error("Failed to determine the workspace directory.");
|
||||
}
|
||||
|
||||
var remoteUrl = getRemoteUrl(absPath);
|
||||
remoteUrl = getRemoteUrl(absPath);
|
||||
const repoName = extractRepoName(remoteUrl);
|
||||
const branch = getCurrentBranch(absPath);
|
||||
const remoteType = getRemoteType(remoteUrl);
|
||||
|
||||
if (!remoteType) {
|
||||
throw new Error("Unable to determine remote type.");
|
||||
}
|
||||
|
||||
const options = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${greptileToken}`,
|
||||
"X-GitHub-Token": githubToken,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
messages: [{ id: "<string>", content: query, role: "user" }],
|
||||
repositories: [
|
||||
{
|
||||
remote: remoteType,
|
||||
branch: branch,
|
||||
repository: repoName,
|
||||
},
|
||||
],
|
||||
sessionId: extras.config.userToken || "default-session",
|
||||
stream: false,
|
||||
genius: true,
|
||||
}),
|
||||
};
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const greptileToken = this.getGreptileToken();
|
||||
if (!greptileToken) {
|
||||
throw new Error("Greptile token not found.");
|
||||
|
||||
try {
|
||||
const response = await extras.fetch(
|
||||
"https://api.greptile.com/v2/query",
|
||||
options,
|
||||
);
|
||||
const rawText = await response.text();
|
||||
|
||||
// Check for HTTP errors
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const githubToken = this.getGithubToken();
|
||||
if (!githubToken) {
|
||||
throw new Error("GitHub token not found.");
|
||||
}
|
||||
|
||||
let absPath = await this.getWorkspaceDir(extras);
|
||||
if (!absPath) {
|
||||
throw new Error("Failed to determine the workspace directory.");
|
||||
}
|
||||
// Parse the response as JSON
|
||||
const json = JSON.parse(rawText);
|
||||
|
||||
var remoteUrl = getRemoteUrl(absPath);
|
||||
remoteUrl = getRemoteUrl(absPath);
|
||||
const repoName = extractRepoName(remoteUrl);
|
||||
const branch = getCurrentBranch(absPath);
|
||||
const remoteType = getRemoteType(remoteUrl);
|
||||
|
||||
if (!remoteType) {
|
||||
throw new Error("Unable to determine remote type.");
|
||||
}
|
||||
|
||||
const options = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${greptileToken}`,
|
||||
"X-GitHub-Token": githubToken,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
messages: [{ id: "<string>", content: query, role: "user" }],
|
||||
repositories: [{
|
||||
remote: remoteType,
|
||||
branch: branch,
|
||||
repository: repoName
|
||||
}],
|
||||
sessionId: extras.config.userToken || "default-session",
|
||||
stream: false,
|
||||
genius: true,
|
||||
}),
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await extras.fetch("https://api.greptile.com/v2/query", options);
|
||||
const rawText = await response.text();
|
||||
|
||||
// Check for HTTP errors
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
// Parse the response as JSON
|
||||
const json = JSON.parse(rawText);
|
||||
|
||||
return json.sources.map((source: any) => ({
|
||||
description: source.filepath,
|
||||
content: `File: ${source.filepath}\nLines: ${source.linestart}-${source.lineend}\n\n${source.summary}`,
|
||||
name: (source.filepath.split("/").pop() ?? "").split("\\").pop() ?? "",
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error("Error getting context items from Greptile:", error);
|
||||
throw new Error("Error getting context items from Greptile");
|
||||
}
|
||||
return json.sources.map((source: any) => ({
|
||||
description: source.filepath,
|
||||
content: `File: ${source.filepath}\nLines: ${source.linestart}-${source.lineend}\n\n${source.summary}`,
|
||||
name: (source.filepath.split("/").pop() ?? "").split("\\").pop() ?? "",
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error("Error getting context items from Greptile:", error);
|
||||
throw new Error("Error getting context items from Greptile");
|
||||
}
|
||||
|
||||
private getGreptileToken(): string | undefined {
|
||||
return this.options.GreptileToken || process.env.GREPTILE_AUTH_TOKEN;
|
||||
}
|
||||
|
||||
private getGreptileToken(): string | undefined {
|
||||
return this.options.GreptileToken || process.env.GREPTILE_AUTH_TOKEN;
|
||||
}
|
||||
|
||||
private getGithubToken(): string | undefined {
|
||||
return this.options.GithubToken || process.env.GITHUB_TOKEN;
|
||||
}
|
||||
|
||||
private async getWorkspaceDir(
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<string | null> {
|
||||
try {
|
||||
const workspaceDirs = await extras.ide.getWorkspaceDirs();
|
||||
if (workspaceDirs && workspaceDirs.length > 0) {
|
||||
return workspaceDirs[0];
|
||||
} else {
|
||||
console.warn(
|
||||
"extras.ide.getWorkspaceDirs() returned undefined or empty array.",
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
"Failed to get workspace directories from extras.ide.getWorkspaceDirs():",
|
||||
);
|
||||
}
|
||||
|
||||
private getGithubToken(): string | undefined {
|
||||
return this.options.GithubToken || process.env.GITHUB_TOKEN;
|
||||
}
|
||||
|
||||
private async getWorkspaceDir(extras: ContextProviderExtras): Promise<string | null> {
|
||||
try {
|
||||
const workspaceDirs = await extras.ide.getWorkspaceDirs();
|
||||
if (workspaceDirs && workspaceDirs.length > 0) {
|
||||
return workspaceDirs[0];
|
||||
} else {
|
||||
console.warn("extras.ide.getWorkspaceDirs() returned undefined or empty array.");
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Failed to get workspace directories from extras.ide.getWorkspaceDirs():");
|
||||
}
|
||||
|
||||
// Fallback to using Git commands
|
||||
try {
|
||||
const currentDir = process.cwd();
|
||||
if (this.isGitRepository(currentDir)) {
|
||||
const workspaceDir = execSync("git rev-parse --show-toplevel").toString().trim();
|
||||
return workspaceDir;
|
||||
} else {
|
||||
console.warn(`Current directory is not a Git repository: ${currentDir}`);
|
||||
return null;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Failed to get workspace directory using Git commands: ");
|
||||
// Fallback to using Git commands
|
||||
try {
|
||||
const currentDir = process.cwd();
|
||||
if (this.isGitRepository(currentDir)) {
|
||||
const workspaceDir = execSync("git rev-parse --show-toplevel")
|
||||
.toString()
|
||||
.trim();
|
||||
return workspaceDir;
|
||||
} else {
|
||||
console.warn(
|
||||
`Current directory is not a Git repository: ${currentDir}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private isGitRepository(dir: string): boolean {
|
||||
try {
|
||||
const gitDir = path.join(dir, ".git");
|
||||
return fs.existsSync(gitDir);
|
||||
} catch (err) {
|
||||
console.warn("Failed to check if directory is a Git repository:");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
function getRemoteUrl(absPath: string): string {
|
||||
try {
|
||||
const remote = execSync(`git -C ${absPath} remote get-url origin`).toString().trim();
|
||||
return remote;
|
||||
} catch (err) {
|
||||
console.warn("Failed to get remote URL");
|
||||
return "";
|
||||
console.warn("Failed to get workspace directory using Git commands: ");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getCurrentBranch(absPath: string): string {
|
||||
|
||||
private isGitRepository(dir: string): boolean {
|
||||
try {
|
||||
const branch = execSync(`git -C ${absPath} rev-parse --abbrev-ref HEAD`).toString().trim();
|
||||
return branch;
|
||||
const gitDir = path.join(dir, ".git");
|
||||
return fs.existsSync(gitDir);
|
||||
} catch (err) {
|
||||
console.warn("Failed to get current branch");
|
||||
return "master"; // Default to 'master' if the current branch cannot be determined
|
||||
console.warn("Failed to check if directory is a Git repository:");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function extractRepoName(remote: string): string {
|
||||
if (remote.startsWith("http://") || remote.startsWith("https://")) {
|
||||
const parts = remote.split("/");
|
||||
if (parts.length >= 2) {
|
||||
return parts[parts.length - 2] + "/" + parts[parts.length - 1].replace(".git", "");
|
||||
}
|
||||
} else if (remote.startsWith("git@")) {
|
||||
const parts = remote.split(":");
|
||||
if (parts.length >= 2) {
|
||||
return parts[1].replace(".git", "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
function getRemoteUrl(absPath: string): string {
|
||||
try {
|
||||
const remote = execSync(`git -C ${absPath} remote get-url origin`)
|
||||
.toString()
|
||||
.trim();
|
||||
return remote;
|
||||
} catch (err) {
|
||||
console.warn("Failed to get remote URL");
|
||||
return "";
|
||||
}
|
||||
|
||||
function getRemoteType(remote: string): string {
|
||||
if (remote.includes("github.com")) {
|
||||
return "github";
|
||||
} else if (remote.includes("gitlab.com")) {
|
||||
return "gitlab";
|
||||
} else if (remote.includes("azure.com")) {
|
||||
return "azure";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function getCurrentBranch(absPath: string): string {
|
||||
try {
|
||||
const branch = execSync(`git -C ${absPath} rev-parse --abbrev-ref HEAD`)
|
||||
.toString()
|
||||
.trim();
|
||||
return branch;
|
||||
} catch (err) {
|
||||
console.warn("Failed to get current branch");
|
||||
return "master"; // Default to 'master' if the current branch cannot be determined
|
||||
}
|
||||
|
||||
export default GreptileContextProvider;
|
||||
|
||||
}
|
||||
|
||||
function extractRepoName(remote: string): string {
|
||||
if (remote.startsWith("http://") || remote.startsWith("https://")) {
|
||||
const parts = remote.split("/");
|
||||
if (parts.length >= 2) {
|
||||
return (
|
||||
parts[parts.length - 2] +
|
||||
"/" +
|
||||
parts[parts.length - 1].replace(".git", "")
|
||||
);
|
||||
}
|
||||
} else if (remote.startsWith("git@")) {
|
||||
const parts = remote.split(":");
|
||||
if (parts.length >= 2) {
|
||||
return parts[1].replace(".git", "");
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function getRemoteType(remote: string): string {
|
||||
if (remote.includes("github.com")) {
|
||||
return "github";
|
||||
} else if (remote.includes("gitlab.com")) {
|
||||
return "gitlab";
|
||||
} else if (remote.includes("azure.com")) {
|
||||
return "azure";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export default GreptileContextProvider;
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import {
|
|||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { getRelativePath } from "../../util/index.js";
|
||||
import { findUriInDirs, getUriPathBasename } from "../../util/uri.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
class OpenFilesContextProvider extends BaseContextProvider {
|
||||
|
|
@ -28,11 +28,10 @@ class OpenFilesContextProvider extends BaseContextProvider {
|
|||
openFiles.map(async (filepath: string) => {
|
||||
return {
|
||||
description: filepath,
|
||||
content: `\`\`\`${await getRelativePath(
|
||||
filepath,
|
||||
workspaceDirs,
|
||||
)}\n${await ide.readFile(filepath)}\n\`\`\``,
|
||||
name: (filepath.split("/").pop() ?? "").split("\\").pop() ?? "",
|
||||
content: `\`\`\`${
|
||||
findUriInDirs(filepath, workspaceDirs).relativePathOrBasename
|
||||
}\n${await ide.readFile(filepath)}\n\`\`\``,
|
||||
name: getUriPathBasename(filepath),
|
||||
uri: {
|
||||
type: "file",
|
||||
value: filepath,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import {
|
|||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { getBasename } from "../../util/index.js";
|
||||
import { getUriPathBasename } from "../../util/uri.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
class ProblemsContextProvider extends BaseContextProvider {
|
||||
|
|
@ -23,6 +23,7 @@ class ProblemsContextProvider extends BaseContextProvider {
|
|||
|
||||
const items = await Promise.all(
|
||||
problems.map(async (problem) => {
|
||||
const fileName = getUriPathBasename(problem.filepath);
|
||||
const content = await ide.readFile(problem.filepath);
|
||||
const lines = content.split("\n");
|
||||
const rangeContent = lines
|
||||
|
|
@ -34,10 +35,8 @@ class ProblemsContextProvider extends BaseContextProvider {
|
|||
|
||||
return {
|
||||
description: "Problems in current file",
|
||||
content: `\`\`\`${getBasename(
|
||||
problem.filepath,
|
||||
)}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`,
|
||||
name: `Warning in ${getBasename(problem.filepath)}`,
|
||||
content: `\`\`\`${fileName}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`,
|
||||
name: `Warning in ${fileName}`,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import {
|
|||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../";
|
||||
import { getAllPromptFilesV2 } from "../../promptFiles/v2/getPromptFiles";
|
||||
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
|
||||
import { parsePreamble } from "../../promptFiles/v2/parse";
|
||||
import { renderPromptFileV2 } from "../../promptFiles/v2/renderPromptFile";
|
||||
|
||||
|
|
@ -38,9 +38,10 @@ class PromptFilesContextProvider extends BaseContextProvider {
|
|||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const promptFiles = await getAllPromptFilesV2(
|
||||
const promptFiles = await getAllPromptFiles(
|
||||
args.ide,
|
||||
args.config.experimental?.promptPath,
|
||||
// Note, NOT checking v1 default folder here, deprecated for context provider
|
||||
);
|
||||
return promptFiles.map((file) => {
|
||||
const preamble = parsePreamble(file.path, file.content);
|
||||
|
|
|
|||
|
|
@ -6,12 +6,12 @@ import {
|
|||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../";
|
||||
import {
|
||||
getBasename,
|
||||
getUniqueFilePath,
|
||||
groupByLastNPathParts,
|
||||
} from "../../util";
|
||||
import { walkDirs } from "../../indexing/walkDir";
|
||||
import generateRepoMap from "../../util/generateRepoMap";
|
||||
import {
|
||||
getShortestUniqueRelativeUriPaths,
|
||||
getUriPathBasename,
|
||||
} from "../../util/uri";
|
||||
|
||||
const ENTIRE_PROJECT_ITEM: ContextSubmenuItem = {
|
||||
id: "entire-codebase",
|
||||
|
|
@ -36,7 +36,9 @@ class RepoMapContextProvider extends BaseContextProvider {
|
|||
name: "Repository Map",
|
||||
description: "Overview of the repository structure",
|
||||
content: await generateRepoMap(extras.llm, extras.ide, {
|
||||
dirs: query === ENTIRE_PROJECT_ITEM.id ? undefined : [query],
|
||||
dirUris: query === ENTIRE_PROJECT_ITEM.id ? undefined : [query],
|
||||
outputRelativeUriPaths: true,
|
||||
includeSignatures: false,
|
||||
}),
|
||||
},
|
||||
];
|
||||
|
|
@ -45,15 +47,25 @@ class RepoMapContextProvider extends BaseContextProvider {
|
|||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const folders = await args.ide.listFolders();
|
||||
const folderGroups = groupByLastNPathParts(folders, 2);
|
||||
const workspaceDirs = await args.ide.getWorkspaceDirs();
|
||||
const folders = await walkDirs(
|
||||
args.ide,
|
||||
{
|
||||
onlyDirs: true,
|
||||
},
|
||||
workspaceDirs,
|
||||
);
|
||||
const withUniquePaths = getShortestUniqueRelativeUriPaths(
|
||||
folders,
|
||||
workspaceDirs,
|
||||
);
|
||||
|
||||
return [
|
||||
ENTIRE_PROJECT_ITEM,
|
||||
...folders.map((folder) => ({
|
||||
id: folder,
|
||||
title: getBasename(folder),
|
||||
description: getUniqueFilePath(folder, folderGroups),
|
||||
...withUniquePaths.map((folder) => ({
|
||||
id: folder.uri,
|
||||
title: getUriPathBasename(folder.uri),
|
||||
description: folder.uniquePath,
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,6 @@ export interface RetrievalPipelineOptions {
|
|||
nRetrieve: number;
|
||||
nFinal: number;
|
||||
tags: BranchAndDir[];
|
||||
pathSep: string;
|
||||
filterDirectory?: string;
|
||||
includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model
|
||||
}
|
||||
|
|
@ -37,8 +36,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
constructor(protected readonly options: RetrievalPipelineOptions) {
|
||||
this.lanceDbIndex = new LanceDbIndex(
|
||||
options.config.embeddingsProvider,
|
||||
(path) => options.ide.readFile(path),
|
||||
options.pathSep,
|
||||
(uri) => options.ide.readFile(uri),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { Chunk } from "../../../";
|
||||
import { findUriInDirs } from "../../../util/uri";
|
||||
import { requestFilesFromRepoMap } from "../repoMapRequest";
|
||||
import { deduplicateChunks } from "../util";
|
||||
|
||||
|
|
@ -44,8 +45,9 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
|
||||
if (filterDirectory) {
|
||||
// Backup if the individual retrieval methods don't listen
|
||||
retrievalResults = retrievalResults.filter((chunk) =>
|
||||
chunk.filepath.startsWith(filterDirectory),
|
||||
retrievalResults = retrievalResults.filter(
|
||||
(chunk) =>
|
||||
!!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Chunk } from "../../..";
|
||||
import { RETRIEVAL_PARAMS } from "../../../util/parameters";
|
||||
import { findUriInDirs } from "../../../util/uri";
|
||||
import { requestFilesFromRepoMap } from "../repoMapRequest";
|
||||
import { deduplicateChunks } from "../util";
|
||||
|
||||
|
|
@ -40,8 +41,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
|
||||
if (filterDirectory) {
|
||||
// Backup if the individual retrieval methods don't listen
|
||||
retrievalResults = retrievalResults.filter((chunk) =>
|
||||
chunk.filepath.startsWith(filterDirectory),
|
||||
retrievalResults = retrievalResults.filter(
|
||||
(chunk) => !!findUriInDirs(chunk.filepath, [filterDirectory]),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../..";
|
|||
import { getModelByRole } from "../../config/util";
|
||||
import generateRepoMap from "../../util/generateRepoMap";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
|
||||
const SUPPORTED_MODEL_TITLE_FAMILIES = [
|
||||
"claude-3",
|
||||
|
|
@ -35,7 +36,7 @@ export async function requestFilesFromRepoMap(
|
|||
config: ContinueConfig,
|
||||
ide: IDE,
|
||||
input: string,
|
||||
filterDirectory?: string,
|
||||
filterDirUri?: string,
|
||||
): Promise<Chunk[]> {
|
||||
const llm = getModelByRole(config, "repoMapFileSelection") ?? defaultLlm;
|
||||
|
||||
|
|
@ -46,8 +47,9 @@ export async function requestFilesFromRepoMap(
|
|||
|
||||
try {
|
||||
const repoMap = await generateRepoMap(llm, ide, {
|
||||
dirUris: filterDirUri ? [filterDirUri] : undefined,
|
||||
includeSignatures: false,
|
||||
dirs: filterDirectory ? [filterDirectory] : undefined,
|
||||
outputRelativeUriPaths: false,
|
||||
});
|
||||
|
||||
const prompt = `${repoMap}
|
||||
|
|
@ -71,25 +73,21 @@ This is the question that you should select relevant files for: "${input}"`;
|
|||
return [];
|
||||
}
|
||||
|
||||
const pathSep = await ide.pathSep();
|
||||
const subDirPrefix = filterDirectory ? filterDirectory + pathSep : "";
|
||||
const files =
|
||||
content
|
||||
.split("<results>")[1]
|
||||
?.split("</results>")[0]
|
||||
?.split("\n")
|
||||
.filter(Boolean)
|
||||
.map((file) => file.trim())
|
||||
.map((file) => subDirPrefix + file) ?? [];
|
||||
const fileUris = content
|
||||
.split("<results>")[1]
|
||||
?.split("</results>")[0]
|
||||
?.split("\n")
|
||||
.filter(Boolean)
|
||||
.map((uri) => uri.trim());
|
||||
|
||||
const chunks = await Promise.all(
|
||||
files.map(async (file) => {
|
||||
const content = await ide.readFile(file);
|
||||
fileUris.map(async (uri) => {
|
||||
const content = await ide.readFile(uri);
|
||||
const lineCount = content.split("\n").length;
|
||||
const chunk: Chunk = {
|
||||
digest: file,
|
||||
digest: uri,
|
||||
content,
|
||||
filepath: file,
|
||||
filepath: uri,
|
||||
endLine: lineCount - 1,
|
||||
startLine: 0,
|
||||
index: 0,
|
||||
|
|
|
|||
|
|
@ -1,8 +1,6 @@
|
|||
import path from "path";
|
||||
|
||||
import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../";
|
||||
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { resolveRelativePathInWorkspace } from "../../util/ideUtils";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils";
|
||||
|
||||
import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline";
|
||||
|
|
@ -71,19 +69,10 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
? RerankerRetrievalPipeline
|
||||
: NoRerankerRetrievalPipeline;
|
||||
|
||||
if (filterDirectory) {
|
||||
// Handle relative paths
|
||||
filterDirectory = await resolveRelativePathInWorkspace(
|
||||
filterDirectory,
|
||||
extras.ide,
|
||||
);
|
||||
}
|
||||
|
||||
const pipelineOptions: RetrievalPipelineOptions = {
|
||||
nFinal,
|
||||
nRetrieve,
|
||||
tags,
|
||||
pathSep: await extras.ide.pathSep(),
|
||||
filterDirectory,
|
||||
ide: extras.ide,
|
||||
input: extras.fullInput,
|
||||
|
|
@ -100,9 +89,17 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
});
|
||||
|
||||
if (results.length === 0) {
|
||||
throw new Error(
|
||||
"Warning: No results found for @codebase context provider.",
|
||||
);
|
||||
if (extras.config.disableIndexing) {
|
||||
void extras.ide.showToast("warning", "No embeddings results found.");
|
||||
return [];
|
||||
} else {
|
||||
void extras.ide.showToast(
|
||||
"warning",
|
||||
"No embeddings results found. If you think this is an error, re-index your codebase.",
|
||||
);
|
||||
// TODO - add "re-index" option to warning message which clears and reindexes codebase
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
|
|
@ -114,13 +111,12 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
...results
|
||||
.sort((a, b) => a.filepath.localeCompare(b.filepath))
|
||||
.map((r) => {
|
||||
const name = `${path.basename(r.filepath)} (${r.startLine}-${
|
||||
r.endLine
|
||||
})`;
|
||||
const basename = getUriPathBasename(r.filepath);
|
||||
const name = `${basename} (${r.startLine}-${r.endLine})`;
|
||||
const description = `${r.filepath}`;
|
||||
|
||||
if (r.filepath.includes("package.json")) {
|
||||
console.log();
|
||||
if (basename === "package.json") {
|
||||
console.warn("Retrieval pipeline: package.json detected");
|
||||
}
|
||||
|
||||
return {
|
||||
|
|
|
|||
75
core/core.ts
75
core/core.ts
|
|
@ -30,14 +30,22 @@ import { logDevData } from "./util/devdata";
|
|||
import { DevDataSqliteDb } from "./util/devdataSqlite";
|
||||
import { GlobalContext } from "./util/GlobalContext";
|
||||
import historyManager from "./util/history";
|
||||
import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths";
|
||||
import {
|
||||
editConfigJson,
|
||||
getConfigJsonPath,
|
||||
setupInitialDotContinueDirectory,
|
||||
} from "./util/paths";
|
||||
import { Telemetry } from "./util/posthog";
|
||||
import { getSymbolsForManyFiles } from "./util/treeSitter";
|
||||
import { TTS } from "./util/tts";
|
||||
|
||||
import { type ContextItemId, type IDE, type IndexingProgressUpdate } from ".";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
|
||||
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile";
|
||||
import type { IMessenger, Message } from "./protocol/messenger";
|
||||
import * as URI from "uri-js";
|
||||
import { localPathToUri } from "./util/pathToUri";
|
||||
|
||||
export class Core {
|
||||
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
|
||||
|
|
@ -698,11 +706,6 @@ export class Core {
|
|||
const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs());
|
||||
await this.refreshCodebaseIndex(dirs);
|
||||
});
|
||||
on("index/forceReIndexFiles", async ({ data }) => {
|
||||
if (data?.files?.length) {
|
||||
await this.refreshCodebaseIndexFiles(data.files);
|
||||
}
|
||||
});
|
||||
on("index/setPaused", (msg) => {
|
||||
this.globalContext.update("indexingPaused", msg.data);
|
||||
this.indexingPauseToken.paused = msg.data;
|
||||
|
|
@ -718,6 +721,66 @@ export class Core {
|
|||
}
|
||||
});
|
||||
|
||||
// File changes
|
||||
// TODO - remove remaining logic for these from IDEs where possible
|
||||
on("files/changed", async ({ data }) => {
|
||||
if (data?.uris?.length) {
|
||||
for (const uri of data.uris) {
|
||||
// Listen for file changes in the workspace
|
||||
// URI TODO is this equality statement valid?
|
||||
if (URI.equal(uri, localPathToUri(getConfigJsonPath()))) {
|
||||
// Trigger a toast notification to provide UI feedback that config has been updated
|
||||
const showToast =
|
||||
this.globalContext.get("showConfigUpdateToast") ?? true;
|
||||
if (showToast) {
|
||||
const selection = await this.ide.showToast(
|
||||
"info",
|
||||
"Config updated",
|
||||
"Don't show again",
|
||||
);
|
||||
if (selection === "Don't show again") {
|
||||
this.globalContext.update("showConfigUpdateToast", false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
uri.endsWith(".continuerc.json") ||
|
||||
uri.endsWith(".prompt") ||
|
||||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE)
|
||||
) {
|
||||
await this.configHandler.reloadConfig();
|
||||
} else if (
|
||||
uri.endsWith(".continueignore") ||
|
||||
uri.endsWith(".gitignore")
|
||||
) {
|
||||
// Reindex the workspaces
|
||||
this.invoke("index/forceReIndex", undefined);
|
||||
} else {
|
||||
// Reindex the file
|
||||
await this.refreshCodebaseIndexFiles([uri]);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
on("files/created", async ({ data }) => {
|
||||
if (data?.uris?.length) {
|
||||
await this.refreshCodebaseIndexFiles(data.uris);
|
||||
}
|
||||
});
|
||||
|
||||
on("files/deleted", async ({ data }) => {
|
||||
if (data?.uris?.length) {
|
||||
await this.refreshCodebaseIndexFiles(data.uris);
|
||||
}
|
||||
});
|
||||
on("files/opened", async ({ data }) => {
|
||||
if (data?.uris?.length) {
|
||||
// Do something on files opened
|
||||
}
|
||||
});
|
||||
|
||||
// Docs, etc. indexing
|
||||
on("indexing/reindex", async (msg) => {
|
||||
if (msg.data.type === "docs") {
|
||||
|
|
|
|||
|
|
@ -1,14 +1,13 @@
|
|||
import path from "path";
|
||||
|
||||
import { DiffLine, ILLM } from "../..";
|
||||
import { generateLines } from "../../diff/util";
|
||||
import { supportedLanguages } from "../../util/treeSitter";
|
||||
import { getUriFileExtension } from "../../util/uri";
|
||||
|
||||
import { deterministicApplyLazyEdit } from "./deterministic";
|
||||
import { streamLazyApply } from "./streamLazyApply";
|
||||
|
||||
function canUseInstantApply(filename: string) {
|
||||
const fileExtension = path.extname(filename).toLowerCase().slice(1);
|
||||
const fileExtension = getUriFileExtension(filename);
|
||||
return supportedLanguages[fileExtension] !== undefined;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,3 @@
|
|||
import path from "path";
|
||||
|
||||
import { distance } from "fastest-levenshtein";
|
||||
import Parser from "web-tree-sitter";
|
||||
|
||||
|
|
@ -9,6 +7,10 @@ import { myersDiff } from "../../diff/myers";
|
|||
import { getParserForFile } from "../../util/treeSitter";
|
||||
|
||||
import { findInAst } from "./findInAst";
|
||||
import {
|
||||
getFileExtensionFromBasename,
|
||||
getUriFileExtension,
|
||||
} from "../../util/uri";
|
||||
|
||||
type AstReplacements = Array<{
|
||||
nodeToReplace: Parser.SyntaxNode;
|
||||
|
|
@ -125,8 +127,8 @@ export async function deterministicApplyLazyEdit(
|
|||
);
|
||||
if (firstSimilarNode?.parent?.equals(oldTree.rootNode)) {
|
||||
// If so, we tack lazy blocks to start and end, and run the usual algorithm
|
||||
const ext = path.extname(filename).slice(1);
|
||||
const language = LANGUAGES[ext];
|
||||
const extension = getFileExtensionFromBasename(filename);
|
||||
const language = LANGUAGES[extension];
|
||||
if (language) {
|
||||
newLazyFile = `${language.singleLineComment} ... existing code ...\n\n${newLazyFile}\n\n${language.singleLineComment} ... existing code...`;
|
||||
newTree = parser.parse(newLazyFile);
|
||||
|
|
|
|||
65
core/index.d.ts
vendored
65
core/index.d.ts
vendored
|
|
@ -1,5 +1,6 @@
|
|||
import Parser from "web-tree-sitter";
|
||||
import { GetGhTokenArgs } from "./protocol/ide";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
ide?: "vscode";
|
||||
|
|
@ -402,7 +403,7 @@ export interface PromptLog {
|
|||
completion: string;
|
||||
}
|
||||
|
||||
type MessageModes = "chat" | "edit";
|
||||
export type MessageModes = "chat" | "edit";
|
||||
|
||||
export type ToolStatus =
|
||||
| "generating"
|
||||
|
|
@ -535,13 +536,13 @@ export interface DiffLine {
|
|||
line: string;
|
||||
}
|
||||
|
||||
export class Problem {
|
||||
export interface Problem {
|
||||
filepath: string;
|
||||
range: Range;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export class Thread {
|
||||
export interface Thread {
|
||||
name: string;
|
||||
id: number;
|
||||
}
|
||||
|
|
@ -605,43 +606,29 @@ export interface IDE {
|
|||
|
||||
getAvailableThreads(): Promise<Thread[]>;
|
||||
|
||||
listFolders(): Promise<string[]>;
|
||||
|
||||
getWorkspaceDirs(): Promise<string[]>;
|
||||
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
|
||||
|
||||
fileExists(filepath: string): Promise<boolean>;
|
||||
fileExists(fileUri: string): Promise<boolean>;
|
||||
|
||||
writeFile(path: string, contents: string): Promise<void>;
|
||||
|
||||
showVirtualFile(title: string, contents: string): Promise<void>;
|
||||
|
||||
getContinueDir(): Promise<string>;
|
||||
|
||||
openFile(path: string): Promise<void>;
|
||||
|
||||
openUrl(url: string): Promise<void>;
|
||||
|
||||
runCommand(command: string): Promise<void>;
|
||||
|
||||
saveFile(filepath: string): Promise<void>;
|
||||
saveFile(fileUri: string): Promise<void>;
|
||||
|
||||
readFile(filepath: string): Promise<string>;
|
||||
readFile(fileUri: string): Promise<string>;
|
||||
|
||||
readRangeInFile(filepath: string, range: Range): Promise<string>;
|
||||
readRangeInFile(fileUri: string, range: Range): Promise<string>;
|
||||
|
||||
showLines(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
): Promise<void>;
|
||||
|
||||
showDiff(
|
||||
filepath: string,
|
||||
newContents: string,
|
||||
stepIndex: number,
|
||||
): Promise<void>;
|
||||
showLines(fileUri: string, startLine: number, endLine: number): Promise<void>;
|
||||
|
||||
getOpenFiles(): Promise<string[]>;
|
||||
|
||||
|
|
@ -660,7 +647,7 @@ export interface IDE {
|
|||
|
||||
subprocess(command: string, cwd?: string): Promise<[string, string]>;
|
||||
|
||||
getProblems(filepath?: string | undefined): Promise<Problem[]>;
|
||||
getProblems(fileUri?: string | undefined): Promise<Problem[]>;
|
||||
|
||||
getBranch(dir: string): Promise<string>;
|
||||
|
||||
|
|
@ -686,9 +673,7 @@ export interface IDE {
|
|||
gotoDefinition(location: Location): Promise<RangeInFile[]>;
|
||||
|
||||
// Callbacks
|
||||
onDidChangeActiveTextEditor(callback: (filepath: string) => void): void;
|
||||
|
||||
pathSep(): Promise<string>;
|
||||
onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void;
|
||||
}
|
||||
|
||||
// Slash Commands
|
||||
|
|
@ -715,7 +700,7 @@ export interface SlashCommand {
|
|||
|
||||
// Config
|
||||
|
||||
type StepName =
|
||||
export type StepName =
|
||||
| "AnswerQuestionChroma"
|
||||
| "GenerateShellCommandStep"
|
||||
| "EditHighlightedCodeStep"
|
||||
|
|
@ -727,7 +712,7 @@ type StepName =
|
|||
| "GenerateShellCommandStep"
|
||||
| "DraftIssueStep";
|
||||
|
||||
type ContextProviderName =
|
||||
export type ContextProviderName =
|
||||
| "diff"
|
||||
| "github"
|
||||
| "terminal"
|
||||
|
|
@ -758,7 +743,7 @@ type ContextProviderName =
|
|||
| "url"
|
||||
| string;
|
||||
|
||||
type TemplateType =
|
||||
export type TemplateType =
|
||||
| "llama2"
|
||||
| "alpaca"
|
||||
| "zephyr"
|
||||
|
|
@ -821,7 +806,7 @@ export interface CustomCommand {
|
|||
description: string;
|
||||
}
|
||||
|
||||
interface Prediction {
|
||||
export interface Prediction {
|
||||
type: "content";
|
||||
content:
|
||||
| string
|
||||
|
|
@ -852,7 +837,7 @@ export interface Tool {
|
|||
uri?: string;
|
||||
}
|
||||
|
||||
interface BaseCompletionOptions {
|
||||
export interface BaseCompletionOptions {
|
||||
temperature?: number;
|
||||
topP?: number;
|
||||
topK?: number;
|
||||
|
|
@ -941,23 +926,23 @@ export interface TabAutocompleteOptions {
|
|||
showWhateverWeHaveAtXMs?: number;
|
||||
}
|
||||
|
||||
interface StdioOptions {
|
||||
export interface StdioOptions {
|
||||
type: "stdio";
|
||||
command: string;
|
||||
args: string[];
|
||||
}
|
||||
|
||||
interface WebSocketOptions {
|
||||
export interface WebSocketOptions {
|
||||
type: "websocket";
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface SSEOptions {
|
||||
export interface SSEOptions {
|
||||
type: "sse";
|
||||
url: string;
|
||||
}
|
||||
|
||||
type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions;
|
||||
export type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions;
|
||||
|
||||
export interface MCPOptions {
|
||||
transport: TransportOptions;
|
||||
|
|
@ -972,7 +957,7 @@ export interface ContinueUIConfig {
|
|||
codeWrap?: boolean;
|
||||
}
|
||||
|
||||
interface ContextMenuConfig {
|
||||
export interface ContextMenuConfig {
|
||||
comment?: string;
|
||||
docstring?: string;
|
||||
fix?: string;
|
||||
|
|
@ -980,7 +965,7 @@ interface ContextMenuConfig {
|
|||
fixGrammar?: string;
|
||||
}
|
||||
|
||||
interface ModelRoles {
|
||||
export interface ModelRoles {
|
||||
inlineEdit?: string;
|
||||
applyCodeBlock?: string;
|
||||
repoMapFileSelection?: string;
|
||||
|
|
@ -1021,7 +1006,7 @@ export type CodeToEdit = RangeInFileWithContents | FileWithContents;
|
|||
* Represents the configuration for a quick action in the Code Lens.
|
||||
* Quick actions are custom commands that can be added to function and class declarations.
|
||||
*/
|
||||
interface QuickActionConfig {
|
||||
export interface QuickActionConfig {
|
||||
/**
|
||||
* The title of the quick action that will display in the Code Lens.
|
||||
*/
|
||||
|
|
@ -1046,7 +1031,7 @@ export type DefaultContextProvider = ContextProviderWithParams & {
|
|||
query?: string;
|
||||
};
|
||||
|
||||
interface ExperimentalConfig {
|
||||
export interface ExperimentalConfig {
|
||||
contextMenuPrompts?: ContextMenuConfig;
|
||||
modelRoles?: ModelRoles;
|
||||
defaultContext?: DefaultContextProvider[];
|
||||
|
|
@ -1073,7 +1058,7 @@ interface ExperimentalConfig {
|
|||
modelContextProtocolServers?: MCPOptions[];
|
||||
}
|
||||
|
||||
interface AnalyticsConfig {
|
||||
export interface AnalyticsConfig {
|
||||
type: string;
|
||||
url?: string;
|
||||
clientKey?: string;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import Parser from "web-tree-sitter";
|
||||
|
||||
import { getBasename, getLastNPathParts } from "../util/";
|
||||
import { migrate } from "../util/paths";
|
||||
import {
|
||||
getFullLanguageName,
|
||||
|
|
@ -29,6 +28,7 @@ import type {
|
|||
IndexTag,
|
||||
IndexingProgressUpdate,
|
||||
} from "../";
|
||||
import { getLastNPathParts, getUriPathBasename } from "../util/uri";
|
||||
|
||||
type SnippetChunk = ChunkWithoutID & { title: string; signature: string };
|
||||
|
||||
|
|
@ -190,6 +190,9 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
const ast = parser.parse(contents);
|
||||
|
||||
const language = getFullLanguageName(filepath);
|
||||
if (!language) {
|
||||
return [];
|
||||
}
|
||||
const query = await getQueryForFile(
|
||||
filepath,
|
||||
`code-snippet-queries/${language}.scm`,
|
||||
|
|
@ -250,7 +253,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
}
|
||||
|
||||
yield {
|
||||
desc: `Indexing ${getBasename(compute.path)}`,
|
||||
desc: `Indexing ${getUriPathBasename(compute.path)}`,
|
||||
progress: i / results.compute.length,
|
||||
status: "indexing",
|
||||
};
|
||||
|
|
@ -353,7 +356,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
return {
|
||||
name: row.title,
|
||||
description: getLastNPathParts(row.path, 2),
|
||||
content: `\`\`\`${getBasename(row.path)}\n${row.content}\n\`\`\``,
|
||||
content: `\`\`\`${getUriPathBasename(row.path)}\n${row.content}\n\`\`\``,
|
||||
uri: {
|
||||
type: "file",
|
||||
value: row.path,
|
||||
|
|
@ -390,7 +393,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
offset: number = 0,
|
||||
batchSize: number = 100,
|
||||
): Promise<{
|
||||
groupedByPath: { [path: string]: string[] };
|
||||
groupedByUri: { [path: string]: string[] };
|
||||
hasMore: boolean;
|
||||
}> {
|
||||
const db = await SqliteDb.get();
|
||||
|
|
@ -411,17 +414,17 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
|
||||
const rows = await db.all(query, [...likePatterns, batchSize, offset]);
|
||||
|
||||
const groupedByPath: { [path: string]: string[] } = {};
|
||||
const groupedByUri: { [path: string]: string[] } = {};
|
||||
|
||||
for (const { path, signature } of rows) {
|
||||
if (!groupedByPath[path]) {
|
||||
groupedByPath[path] = [];
|
||||
if (!groupedByUri[path]) {
|
||||
groupedByUri[path] = [];
|
||||
}
|
||||
groupedByPath[path].push(signature);
|
||||
groupedByUri[path].push(signature);
|
||||
}
|
||||
|
||||
const hasMore = rows.length === batchSize;
|
||||
|
||||
return { groupedByPath, hasMore };
|
||||
return { groupedByUri, hasMore };
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import { execSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import path from "path";
|
||||
import { jest } from "@jest/globals";
|
||||
|
||||
import { ContinueServerClient } from "../continueServer/stubs/client.js";
|
||||
|
|
@ -11,6 +10,7 @@ import {
|
|||
setUpTestDir,
|
||||
tearDownTestDir,
|
||||
TEST_DIR,
|
||||
TEST_DIR_PATH,
|
||||
} from "../test/testDir.js";
|
||||
import { getIndexSqlitePath } from "../util/paths.js";
|
||||
|
||||
|
|
@ -19,6 +19,8 @@ import { getComputeDeleteAddRemove } from "./refreshIndex.js";
|
|||
import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
|
||||
import { CodebaseIndex } from "./types.js";
|
||||
import { walkDir } from "./walkDir.js";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { joinPathsToUri } from "../util/uri.js";
|
||||
|
||||
jest.useFakeTimers();
|
||||
|
||||
|
|
@ -75,9 +77,11 @@ describe("CodebaseIndexer", () => {
|
|||
tearDownTestDir();
|
||||
setUpTestDir();
|
||||
|
||||
execSync("git init", { cwd: TEST_DIR });
|
||||
execSync('git config user.email "test@example.com"', { cwd: TEST_DIR });
|
||||
execSync('git config user.name "Test"', { cwd: TEST_DIR });
|
||||
execSync("git init", { cwd: TEST_DIR_PATH });
|
||||
execSync('git config user.email "test@example.com"', {
|
||||
cwd: TEST_DIR_PATH,
|
||||
});
|
||||
execSync('git config user.name "Test"', { cwd: TEST_DIR_PATH });
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
|
|
@ -155,7 +159,10 @@ describe("CodebaseIndexer", () => {
|
|||
});
|
||||
|
||||
test("should have created index folder with all necessary files", async () => {
|
||||
expect(fs.existsSync(getIndexSqlitePath())).toBe(true);
|
||||
const exists = await testIde.fileExists(
|
||||
pathToFileURL(getIndexSqlitePath()).toString(),
|
||||
);
|
||||
expect(exists).toBe(true);
|
||||
});
|
||||
|
||||
test("should have indexed all of the files", async () => {
|
||||
|
|
@ -189,7 +196,7 @@ describe("CodebaseIndexer", () => {
|
|||
});
|
||||
|
||||
test("should successfully re-index after deleting a file", async () => {
|
||||
fs.rmSync(path.join(TEST_DIR, "main.rs"));
|
||||
fs.rmSync(path.join(TEST_DIR_PATH, "main.rs"));
|
||||
|
||||
await expectPlan(0, 0, 0, 1);
|
||||
|
||||
|
|
@ -210,23 +217,25 @@ describe("CodebaseIndexer", () => {
|
|||
|
||||
test("should create git repo for testing", async () => {
|
||||
execSync(
|
||||
`cd ${TEST_DIR} && git init && git checkout -b main && git add -A && git commit -m "First commit"`,
|
||||
`cd ${TEST_DIR_PATH} && git init && git checkout -b main && git add -A && git commit -m "First commit"`,
|
||||
);
|
||||
});
|
||||
|
||||
test.skip("should only re-index the changed files when changing branches", async () => {
|
||||
execSync(`cd ${TEST_DIR} && git checkout -b test2`);
|
||||
execSync(`cd ${TEST_DIR_PATH} && git checkout -b test2`);
|
||||
// Rewriting the file
|
||||
addToTestDir([["test.ts", "// This is different"]]);
|
||||
|
||||
// Should re-compute test.ts, but just re-tag the .py file
|
||||
await expectPlan(1, 1, 0, 0);
|
||||
|
||||
execSync(`cd ${TEST_DIR} && git add -A && git commit -m "Change .ts file"`);
|
||||
execSync(
|
||||
`cd ${TEST_DIR_PATH} && git add -A && git commit -m "Change .ts file"`,
|
||||
);
|
||||
});
|
||||
|
||||
test.skip("shouldn't re-index anything when changing back to original branch", async () => {
|
||||
execSync(`cd ${TEST_DIR} && git checkout main`);
|
||||
execSync(`cd ${TEST_DIR_PATH} && git checkout main`);
|
||||
await expectPlan(0, 0, 0, 0);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import {
|
|||
RefreshIndexResults,
|
||||
} from "./types.js";
|
||||
import { walkDirAsync } from "./walkDir.js";
|
||||
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
|
||||
|
||||
export class PauseToken {
|
||||
constructor(private _paused: boolean) {}
|
||||
|
|
@ -75,19 +76,15 @@ export class CodebaseIndexer {
|
|||
|
||||
protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
|
||||
const config = await this.configHandler.loadConfig();
|
||||
const pathSep = await this.ide.pathSep();
|
||||
|
||||
const indexes = [
|
||||
new ChunkCodebaseIndex(
|
||||
this.ide.readFile.bind(this.ide),
|
||||
pathSep,
|
||||
this.continueServerClient,
|
||||
config.embeddingsProvider.maxEmbeddingChunkSize,
|
||||
), // Chunking must come first
|
||||
new LanceDbIndex(
|
||||
config.embeddingsProvider,
|
||||
this.ide.readFile.bind(this.ide),
|
||||
pathSep,
|
||||
this.continueServerClient,
|
||||
),
|
||||
new FullTextSearchCodebaseIndex(),
|
||||
|
|
@ -97,23 +94,26 @@ export class CodebaseIndexer {
|
|||
return indexes;
|
||||
}
|
||||
|
||||
public async refreshFile(file: string): Promise<void> {
|
||||
public async refreshFile(
|
||||
file: string,
|
||||
workspaceDirs: string[],
|
||||
): Promise<void> {
|
||||
if (this.pauseToken.paused) {
|
||||
// NOTE: by returning here, there is a chance that while paused a file is modified and
|
||||
// then after unpausing the file is not reindexed
|
||||
return;
|
||||
}
|
||||
const workspaceDir = await this.getWorkspaceDir(file);
|
||||
if (!workspaceDir) {
|
||||
const { foundInDir } = findUriInDirs(file, workspaceDirs);
|
||||
if (!foundInDir) {
|
||||
return;
|
||||
}
|
||||
const branch = await this.ide.getBranch(workspaceDir);
|
||||
const repoName = await this.ide.getRepoName(workspaceDir);
|
||||
const branch = await this.ide.getBranch(foundInDir);
|
||||
const repoName = await this.ide.getRepoName(foundInDir);
|
||||
const indexesToBuild = await this.getIndexesToBuild();
|
||||
const stats = await this.ide.getLastModified([file]);
|
||||
for (const index of indexesToBuild) {
|
||||
const tag = {
|
||||
directory: workspaceDir,
|
||||
directory: foundInDir,
|
||||
branch,
|
||||
artifactId: index.artifactId,
|
||||
};
|
||||
|
|
@ -154,6 +154,8 @@ export class CodebaseIndexer {
|
|||
};
|
||||
}
|
||||
|
||||
const workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
|
||||
const progressPer = 1 / files.length;
|
||||
try {
|
||||
for (const file of files) {
|
||||
|
|
@ -162,7 +164,7 @@ export class CodebaseIndexer {
|
|||
desc: `Indexing file ${file}...`,
|
||||
status: "indexing",
|
||||
};
|
||||
await this.refreshFile(file);
|
||||
await this.refreshFile(file, workspaceDirs);
|
||||
|
||||
progress += progressPer;
|
||||
|
||||
|
|
@ -224,7 +226,7 @@ export class CodebaseIndexer {
|
|||
const beginTime = Date.now();
|
||||
|
||||
for (const directory of dirs) {
|
||||
const dirBasename = await this.basename(directory);
|
||||
const dirBasename = getUriPathBasename(directory);
|
||||
yield {
|
||||
progress,
|
||||
desc: `Discovering files in ${dirBasename}...`,
|
||||
|
|
@ -446,20 +448,4 @@ export class CodebaseIndexer {
|
|||
completedIndexCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async getWorkspaceDir(filepath: string): Promise<string | undefined> {
|
||||
const workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
for (const workspaceDir of workspaceDirs) {
|
||||
if (filepath.startsWith(workspaceDir)) {
|
||||
return workspaceDir;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private async basename(filepath: string): Promise<string> {
|
||||
const pathSep = await this.ide.pathSep();
|
||||
const path = filepath.split(pathSep);
|
||||
return path[path.length - 1];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../";
|
||||
import { getBasename } from "../util/index";
|
||||
import { RETRIEVAL_PARAMS } from "../util/parameters";
|
||||
import { getUriPathBasename } from "../util/uri";
|
||||
|
||||
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
|
||||
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
|
||||
|
|
@ -79,7 +79,7 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
|
|||
|
||||
yield {
|
||||
progress: i / results.compute.length,
|
||||
desc: `Indexing ${getBasename(item.path)}`,
|
||||
desc: `Indexing ${getUriPathBasename(item.path)}`,
|
||||
status: "indexing",
|
||||
};
|
||||
await markComplete([item], IndexResultType.Compute);
|
||||
|
|
|
|||
|
|
@ -26,13 +26,11 @@ describe.skip("ChunkCodebaseIndex", () => {
|
|||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
const pathSep = await testIde.pathSep();
|
||||
const mockConfig = await testConfigHandler.loadConfig();
|
||||
|
||||
index = new LanceDbIndex(
|
||||
mockConfig.embeddingsProvider,
|
||||
testIde.readFile.bind(testIde),
|
||||
pathSep,
|
||||
testContinueServerClient,
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@ import {
|
|||
IndexTag,
|
||||
IndexingProgressUpdate,
|
||||
} from "../index.js";
|
||||
import { getBasename } from "../util/index.js";
|
||||
import { getLanceDbPath, migrate } from "../util/paths.js";
|
||||
|
||||
import { chunkDocument, shouldChunk } from "./chunk/chunk.js";
|
||||
|
|
@ -23,6 +22,7 @@ import {
|
|||
PathAndCacheKey,
|
||||
RefreshIndexResults,
|
||||
} from "./types.js";
|
||||
import { getUriPathBasename } from "../util/uri.js";
|
||||
|
||||
// LanceDB converts to lowercase, so names must all be lowercase
|
||||
interface LanceDbRow {
|
||||
|
|
@ -46,7 +46,6 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
constructor(
|
||||
private readonly embeddingsProvider: ILLM,
|
||||
private readonly readFile: (filepath: string) => Promise<string>,
|
||||
private readonly pathSep: string,
|
||||
private readonly continueServerClient?: IContinueServerClient,
|
||||
) {}
|
||||
|
||||
|
|
@ -125,7 +124,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
try {
|
||||
const content = await this.readFile(item.path);
|
||||
|
||||
if (!shouldChunk(this.pathSep, item.path, content)) {
|
||||
if (!shouldChunk(item.path, content)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -350,7 +349,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
accumulatedProgress += 1 / results.addTag.length / 3;
|
||||
yield {
|
||||
progress: accumulatedProgress,
|
||||
desc: `Indexing ${getBasename(path)}`,
|
||||
desc: `Indexing ${getUriPathBasename(path)}`,
|
||||
status: "indexing",
|
||||
};
|
||||
}
|
||||
|
|
@ -372,7 +371,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
accumulatedProgress += 1 / toDel.length / 3;
|
||||
yield {
|
||||
progress: accumulatedProgress,
|
||||
desc: `Stashing ${getBasename(path)}`,
|
||||
desc: `Stashing ${getUriPathBasename(path)}`,
|
||||
status: "indexing",
|
||||
};
|
||||
}
|
||||
|
|
@ -391,7 +390,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
accumulatedProgress += 1 / results.del.length / 3;
|
||||
yield {
|
||||
progress: accumulatedProgress,
|
||||
desc: `Removing ${getBasename(path)}`,
|
||||
desc: `Removing ${getUriPathBasename(path)}`,
|
||||
status: "indexing",
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,11 +29,8 @@ describe("ChunkCodebaseIndex", () => {
|
|||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
const pathSep = await testIde.pathSep();
|
||||
|
||||
index = new ChunkCodebaseIndex(
|
||||
testIde.readFile.bind(testIde),
|
||||
pathSep,
|
||||
testContinueServerClient,
|
||||
1000,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import { RunResult } from "sqlite3";
|
|||
|
||||
import { IContinueServerClient } from "../../continueServer/interface.js";
|
||||
import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js";
|
||||
import { getBasename } from "../../util/index.js";
|
||||
import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex.js";
|
||||
import {
|
||||
IndexResultType,
|
||||
|
|
@ -15,6 +14,7 @@ import {
|
|||
} from "../types.js";
|
||||
|
||||
import { chunkDocument, shouldChunk } from "./chunk.js";
|
||||
import { getUriPathBasename } from "../../util/uri.js";
|
||||
|
||||
export class ChunkCodebaseIndex implements CodebaseIndex {
|
||||
relativeExpectedTime: number = 1;
|
||||
|
|
@ -23,7 +23,6 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
|
|||
|
||||
constructor(
|
||||
private readonly readFile: (filepath: string) => Promise<string>,
|
||||
private readonly pathSep: string,
|
||||
private readonly continueServerClient: IContinueServerClient,
|
||||
private readonly maxChunkSize: number,
|
||||
) {}
|
||||
|
|
@ -89,7 +88,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
|
|||
accumulatedProgress += 1 / results.addTag.length / 4;
|
||||
yield {
|
||||
progress: accumulatedProgress,
|
||||
desc: `Adding ${getBasename(item.path)}`,
|
||||
desc: `Adding ${getUriPathBasename(item.path)}`,
|
||||
status: "indexing",
|
||||
};
|
||||
}
|
||||
|
|
@ -111,7 +110,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
|
|||
accumulatedProgress += 1 / results.removeTag.length / 4;
|
||||
yield {
|
||||
progress: accumulatedProgress,
|
||||
desc: `Removing ${getBasename(item.path)}`,
|
||||
desc: `Removing ${getUriPathBasename(item.path)}`,
|
||||
status: "indexing",
|
||||
};
|
||||
}
|
||||
|
|
@ -138,7 +137,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
|
|||
accumulatedProgress += 1 / results.del.length / 4;
|
||||
yield {
|
||||
progress: accumulatedProgress,
|
||||
desc: `Removing ${getBasename(item.path)}`,
|
||||
desc: `Removing ${getUriPathBasename(item.path)}`,
|
||||
status: "indexing",
|
||||
};
|
||||
}
|
||||
|
|
@ -165,7 +164,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
|
|||
|
||||
private async packToChunks(pack: PathAndCacheKey): Promise<Chunk[]> {
|
||||
const contents = await this.readFile(pack.path);
|
||||
if (!shouldChunk(this.pathSep, pack.path, contents)) {
|
||||
if (!shouldChunk(pack.path, contents)) {
|
||||
return [];
|
||||
}
|
||||
const chunks: Chunk[] = [];
|
||||
|
|
|
|||
|
|
@ -6,25 +6,25 @@ describe("shouldChunk", () => {
|
|||
test("should chunk a typescript file", () => {
|
||||
const filePath = path.join("directory", "file.ts");
|
||||
const fileContent = generateString(10000);
|
||||
expect(shouldChunk(path.sep, filePath, fileContent)).toBe(true);
|
||||
expect(shouldChunk(filePath, fileContent)).toBe(true);
|
||||
});
|
||||
|
||||
test("should not chunk a large typescript file", () => {
|
||||
const filePath = path.join("directory", "file.ts");
|
||||
const fileContent = generateString(1500000);
|
||||
expect(shouldChunk(path.sep, filePath, fileContent)).toBe(false);
|
||||
expect(shouldChunk(filePath, fileContent)).toBe(false);
|
||||
});
|
||||
|
||||
test("should not chunk an empty file", () => {
|
||||
const filePath = path.join("directory", "file.ts");
|
||||
const fileContent = generateString(0);
|
||||
expect(shouldChunk(path.sep, filePath, fileContent)).toBe(false);
|
||||
expect(shouldChunk(filePath, fileContent)).toBe(false);
|
||||
});
|
||||
|
||||
test("should not chunk a file without extension", () => {
|
||||
const filePath = path.join("directory", "with.dot", "filename");
|
||||
const fileContent = generateString(10000);
|
||||
expect(shouldChunk(path.sep, filePath, fileContent)).toBe(false);
|
||||
expect(shouldChunk(filePath, fileContent)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { countTokensAsync } from "../../llm/countTokens.js";
|
|||
import { extractMinimalStackTraceInfo } from "../../util/extractMinimalStackTraceInfo.js";
|
||||
import { Telemetry } from "../../util/posthog.js";
|
||||
import { supportedLanguages } from "../../util/treeSitter.js";
|
||||
import { getUriFileExtension, getUriPathBasename } from "../../util/uri.js";
|
||||
|
||||
import { basicChunker } from "./basic.js";
|
||||
import { codeChunker } from "./code.js";
|
||||
|
|
@ -15,25 +16,23 @@ export type ChunkDocumentParam = {
|
|||
};
|
||||
|
||||
async function* chunkDocumentWithoutId(
|
||||
filepath: string,
|
||||
fileUri: string,
|
||||
contents: string,
|
||||
maxChunkSize: number,
|
||||
): AsyncGenerator<ChunkWithoutID> {
|
||||
if (contents.trim() === "") {
|
||||
return;
|
||||
}
|
||||
|
||||
const segs = filepath.split(".");
|
||||
const ext = segs[segs.length - 1];
|
||||
if (ext in supportedLanguages) {
|
||||
const extension = getUriFileExtension(fileUri);
|
||||
if (extension in supportedLanguages) {
|
||||
try {
|
||||
for await (const chunk of codeChunker(filepath, contents, maxChunkSize)) {
|
||||
for await (const chunk of codeChunker(fileUri, contents, maxChunkSize)) {
|
||||
yield chunk;
|
||||
}
|
||||
return;
|
||||
} catch (e: any) {
|
||||
Telemetry.capture("code_chunker_error", {
|
||||
fileExtension: ext,
|
||||
void Telemetry.capture("code_chunker_error", {
|
||||
fileExtension: extension,
|
||||
stack: extractMinimalStackTraceInfo(e.stack),
|
||||
});
|
||||
// falls back to basicChunker
|
||||
|
|
@ -84,11 +83,7 @@ export async function* chunkDocument({
|
|||
}
|
||||
}
|
||||
|
||||
export function shouldChunk(
|
||||
pathSep: string,
|
||||
filepath: string,
|
||||
contents: string,
|
||||
): boolean {
|
||||
export function shouldChunk(fileUri: string, contents: string): boolean {
|
||||
if (contents.length > 1000000) {
|
||||
// if a file has more than 1m characters then skip it
|
||||
return false;
|
||||
|
|
@ -96,7 +91,6 @@ export function shouldChunk(
|
|||
if (contents.length === 0) {
|
||||
return false;
|
||||
}
|
||||
const basename = filepath.split(pathSep).pop();
|
||||
// files without extensions are often binary files, skip it if so
|
||||
return basename?.includes(".") ?? false;
|
||||
const baseName = getUriPathBasename(fileUri);
|
||||
return baseName.includes(".");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,6 +31,11 @@ function breakdownArticleComponent(
|
|||
let content = "";
|
||||
let index = 0;
|
||||
|
||||
const fullUrl = new URL(
|
||||
`${subpath}#${cleanFragment(article.title)}`,
|
||||
url,
|
||||
).toString();
|
||||
|
||||
const createChunk = (
|
||||
chunkContent: string,
|
||||
chunkStartLine: number,
|
||||
|
|
@ -44,11 +49,8 @@ function breakdownArticleComponent(
|
|||
title: cleanHeader(article.title),
|
||||
},
|
||||
index: index++,
|
||||
filepath: new URL(
|
||||
`${subpath}#${cleanFragment(article.title)}`,
|
||||
url,
|
||||
).toString(),
|
||||
digest: subpath,
|
||||
filepath: fullUrl,
|
||||
digest: fullUrl,
|
||||
});
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -348,6 +348,11 @@ const preIndexedDocs: Record<
|
|||
rootUrl: "https://api.dart.dev",
|
||||
faviconUrl: "https://api.dart.dev/static-assets/favicon.png",
|
||||
},
|
||||
"https://docs.asksage.ai/": {
|
||||
title: "Ask Sage",
|
||||
startUrl: "https://docs.asksage.ai/",
|
||||
rootUrl: "https://docs.asksage.ai/",
|
||||
},
|
||||
};
|
||||
|
||||
export default preIndexedDocs;
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@ import {
|
|||
PackageDetails,
|
||||
ParsedPackageInfo,
|
||||
} from "../../..";
|
||||
import { walkDir } from "../../walkDir";
|
||||
import { getUriPathBasename } from "../../../util/uri";
|
||||
import { walkDir, walkDirs } from "../../walkDir";
|
||||
|
||||
import { PythonPackageCrawler } from "./packageCrawlers/Python";
|
||||
import { NodePackageCrawler } from "./packageCrawlers/TsJs";
|
||||
|
|
@ -24,16 +25,10 @@ export interface PackageCrawler {
|
|||
}
|
||||
|
||||
export async function getAllSuggestedDocs(ide: IDE) {
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
const results = await Promise.all(
|
||||
workspaceDirs.map((dir) => {
|
||||
return walkDir(dir, ide);
|
||||
}),
|
||||
);
|
||||
const allPaths = results.flat(); // TODO only get files, not dirs. Not critical for now
|
||||
const allFiles = allPaths.map((path) => ({
|
||||
path,
|
||||
name: path.split(/[\\/]/).pop()!,
|
||||
const allFileUris = await walkDirs(ide);
|
||||
const allFiles = allFileUris.map((uri) => ({
|
||||
path: uri,
|
||||
name: getUriPathBasename(uri),
|
||||
}));
|
||||
|
||||
// Build map of language -> package files
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { IndexTag } from "../..";
|
|||
import { IContinueServerClient } from "../../continueServer/interface";
|
||||
import { ChunkCodebaseIndex } from "../chunk/ChunkCodebaseIndex";
|
||||
import { tagToString } from "../refreshIndex";
|
||||
import { CodebaseIndex, PathAndCacheKey, RefreshIndexResults } from "../types";
|
||||
import { CodebaseIndex, RefreshIndexResults } from "../types";
|
||||
|
||||
import { testIde } from "../../test/fixtures";
|
||||
import { addToTestDir, TEST_DIR } from "../../test/testDir";
|
||||
|
|
@ -54,11 +54,8 @@ const mockMarkComplete = jest
|
|||
.mockImplementation(() => Promise.resolve()) as any;
|
||||
|
||||
export async function insertMockChunks() {
|
||||
const pathSep = await testIde.pathSep();
|
||||
|
||||
const index = new ChunkCodebaseIndex(
|
||||
testIde.readFile.bind(testIde),
|
||||
pathSep,
|
||||
mockContinueServerClient,
|
||||
1000,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,360 +1,357 @@
|
|||
import path from "path";
|
||||
|
||||
import { walkDir, WalkerOptions } from "../indexing/walkDir";
|
||||
// Generated by continue
|
||||
import { testIde } from "../test/fixtures";
|
||||
import {
|
||||
TEST_DIR,
|
||||
setUpTestDir,
|
||||
tearDownTestDir,
|
||||
addToTestDir,
|
||||
TEST_DIR_PATH,
|
||||
} from "../test/testDir";
|
||||
import FileSystemIde from "../util/filesystem";
|
||||
import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
const ide = new FileSystemIde(TEST_DIR);
|
||||
|
||||
async function walkTestDir(
|
||||
options?: WalkerOptions,
|
||||
): Promise<string[] | undefined> {
|
||||
return walkDir(TEST_DIR, ide, {
|
||||
returnRelativePaths: true,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
|
||||
async function expectPaths(
|
||||
toExist: string[],
|
||||
toNotExist: string[],
|
||||
options?: WalkerOptions,
|
||||
) {
|
||||
// Convert to Windows paths
|
||||
const pathSep = await ide.pathSep();
|
||||
if (pathSep === "\\") {
|
||||
toExist = toExist.map((p) => p.replace(/\//g, "\\"));
|
||||
toNotExist = toNotExist.map((p) => p.replace(/\//g, "\\"));
|
||||
}
|
||||
|
||||
const result = await walkTestDir(options);
|
||||
|
||||
for (const p of toExist) {
|
||||
expect(result).toContain(p);
|
||||
}
|
||||
for (const p of toNotExist) {
|
||||
expect(result).not.toContain(p);
|
||||
}
|
||||
}
|
||||
|
||||
describe("walkDir", () => {
|
||||
beforeEach(() => {
|
||||
describe("walkDir functions", () => {
|
||||
beforeEach(async () => {
|
||||
setUpTestDir();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
afterEach(async () => {
|
||||
tearDownTestDir();
|
||||
});
|
||||
|
||||
test("should return nothing for empty dir", async () => {
|
||||
const result = await walkTestDir();
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
describe("walkDir", () => {
|
||||
it("should walk a simple directory structure", async () => {
|
||||
addToTestDir([
|
||||
"src/",
|
||||
["src/file1.ts", "content1"],
|
||||
["src/file2.ts", "content2"],
|
||||
"src/nested/",
|
||||
["src/nested/file3.ts", "content3"],
|
||||
]);
|
||||
|
||||
test("should return all files in flat dir", async () => {
|
||||
const files = ["a.txt", "b.py", "c.ts"];
|
||||
addToTestDir(files);
|
||||
const result = await walkTestDir();
|
||||
expect(result).toEqual(files);
|
||||
});
|
||||
const files = await walkDir(
|
||||
(await testIde.getWorkspaceDirs())[0],
|
||||
testIde,
|
||||
);
|
||||
|
||||
test("should ignore ignored files in flat dir", async () => {
|
||||
const files = [[".gitignore", "*.py"], "a.txt", "c.ts", "b.py"];
|
||||
addToTestDir(files);
|
||||
await expectPaths(["a.txt", "c.ts"], ["b.py"]);
|
||||
});
|
||||
|
||||
test("should handle negation in flat folder", async () => {
|
||||
const files = [[".gitignore", "**/*\n!*.py"], "a.txt", "c.ts", "b.py"];
|
||||
addToTestDir(files);
|
||||
await expectPaths(["b.py"], [".gitignore", "a.txt", "c.ts"]);
|
||||
});
|
||||
|
||||
test("should get all files in nested folder structure", async () => {
|
||||
const files = [
|
||||
"a.txt",
|
||||
"b.py",
|
||||
"c.ts",
|
||||
"d/",
|
||||
"d/e.txt",
|
||||
"d/f.py",
|
||||
"d/g/",
|
||||
"d/g/h.ts",
|
||||
];
|
||||
addToTestDir(files);
|
||||
await expectPaths(
|
||||
files.filter((files) => !files.endsWith("/")),
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
test("should ignore ignored files in nested folder structure", async () => {
|
||||
const files = [
|
||||
"a.txt",
|
||||
"b.py",
|
||||
"c.ts",
|
||||
"d/",
|
||||
"d/e.txt",
|
||||
"d/f.py",
|
||||
"d/g/",
|
||||
"d/g/h.ts",
|
||||
["d/.gitignore", "*.py"],
|
||||
];
|
||||
addToTestDir(files);
|
||||
await expectPaths(
|
||||
["a.txt", "b.py", "c.ts", "d/e.txt", "d/g/h.ts"],
|
||||
["d/f.py"],
|
||||
);
|
||||
});
|
||||
|
||||
test("should use gitignore in parent directory for subdirectory", async () => {
|
||||
const files = [
|
||||
"a.txt",
|
||||
"b.py",
|
||||
"d/",
|
||||
"d/e.txt",
|
||||
"d/f.py",
|
||||
"d/g/",
|
||||
"d/g/h.ts",
|
||||
"d/g/i.py",
|
||||
[".gitignore", "*.py"],
|
||||
];
|
||||
addToTestDir(files);
|
||||
await expectPaths(["a.txt", "d/e.txt", "d/g/h.ts"], ["d/f.py", "d/g/i.py"]);
|
||||
});
|
||||
|
||||
test("should handle leading slash in gitignore", async () => {
|
||||
const files = [[".gitignore", "/no.txt"], "a.txt", "b.py", "no.txt"];
|
||||
addToTestDir(files);
|
||||
await expectPaths(["a.txt", "b.py"], ["no.txt"]);
|
||||
});
|
||||
|
||||
test("should not ignore leading slash when in subfolder", async () => {
|
||||
const files = [
|
||||
[".gitignore", "/no.txt"],
|
||||
"a.txt",
|
||||
"b.py",
|
||||
"no.txt",
|
||||
"sub/",
|
||||
"sub/no.txt",
|
||||
];
|
||||
addToTestDir(files);
|
||||
await expectPaths(["a.txt", "b.py", "sub/no.txt"], ["no.txt"]);
|
||||
});
|
||||
|
||||
test("should handle multiple .gitignore files in nested structure", async () => {
|
||||
const files = [
|
||||
[".gitignore", "*.txt"],
|
||||
"a.py",
|
||||
"b.txt",
|
||||
"c/",
|
||||
"c/d.txt",
|
||||
"c/e.py",
|
||||
["c/.gitignore", "*.py"],
|
||||
];
|
||||
addToTestDir(files);
|
||||
await expectPaths(["a.py"], ["b.txt", "c/e.py", "c/d.txt"]);
|
||||
});
|
||||
|
||||
test("should handle wildcards in .gitignore", async () => {
|
||||
const files = [
|
||||
[".gitignore", "*.txt\n*.py"],
|
||||
"a.txt",
|
||||
"b.py",
|
||||
"c.ts",
|
||||
"d/",
|
||||
"d/e.txt",
|
||||
"d/f.py",
|
||||
"d/g.ts",
|
||||
];
|
||||
addToTestDir(files);
|
||||
await expectPaths(
|
||||
["c.ts", "d/g.ts"],
|
||||
["a.txt", "b.py", "d/e.txt", "d/f.py"],
|
||||
);
|
||||
});
|
||||
|
||||
test("should handle directory ignores in .gitignore", async () => {
|
||||
const files = [
|
||||
[".gitignore", "ignored_dir/"],
|
||||
"a.txt",
|
||||
"ignored_dir/",
|
||||
"ignored_dir/b.txt",
|
||||
"ignored_dir/c/",
|
||||
"ignored_dir/c/d.py",
|
||||
];
|
||||
addToTestDir(files);
|
||||
await expectPaths(["a.txt"], ["ignored_dir/b.txt", "ignored_dir/c/d.py"]);
|
||||
});
|
||||
|
||||
test("gitignore in sub directory should only apply to subdirectory", async () => {
|
||||
const files = [
|
||||
[".gitignore", "abc"],
|
||||
"a.txt",
|
||||
"abc",
|
||||
"xyz/",
|
||||
["xyz/.gitignore", "xyz"],
|
||||
"xyz/b.txt",
|
||||
"xyz/c/",
|
||||
"xyz/c/d.py",
|
||||
"xyz/xyz",
|
||||
];
|
||||
addToTestDir(files);
|
||||
await expectPaths(["a.txt", "xyz/b.txt", "xyz/c/d.py"], ["abc", "xyz/xyz"]);
|
||||
});
|
||||
|
||||
test("should handle complex patterns in .gitignore", async () => {
|
||||
const files = [
|
||||
[".gitignore", "*.what\n!important.what\ntemp/\n/root_only.txt"],
|
||||
"a.what",
|
||||
"important.what",
|
||||
"root_only.txt",
|
||||
"subdir/",
|
||||
"subdir/root_only.txt",
|
||||
"subdir/b.what",
|
||||
"temp/",
|
||||
"temp/c.txt",
|
||||
];
|
||||
addToTestDir(files);
|
||||
await expectPaths(
|
||||
["important.what", "subdir/root_only.txt"],
|
||||
["a.what", "root_only.txt", "subdir/b.what", "temp/c.txt"],
|
||||
);
|
||||
});
|
||||
|
||||
test("should listen to both .gitignore and .continueignore", async () => {
|
||||
const files = [
|
||||
[".gitignore", "*.py"],
|
||||
[".continueignore", "*.ts"],
|
||||
"a.txt",
|
||||
"b.py",
|
||||
"c.ts",
|
||||
"d.js",
|
||||
];
|
||||
addToTestDir(files);
|
||||
await expectPaths(["a.txt", "d.js"], ["b.py", "c.ts"]);
|
||||
});
|
||||
|
||||
test("should return dirs and only dirs in onlyDirs mode", async () => {
|
||||
const files = [
|
||||
"a.txt",
|
||||
"b.py",
|
||||
"c.ts",
|
||||
"d/",
|
||||
"d/e.txt",
|
||||
"d/f.py",
|
||||
"d/g/",
|
||||
"d/g/h.ts",
|
||||
];
|
||||
addToTestDir(files);
|
||||
await expectPaths(
|
||||
["d", "d/g"],
|
||||
["a.txt", "b.py", "c.ts", "d/e.txt", "d/f.py", "d/g/h.ts"],
|
||||
{ onlyDirs: true },
|
||||
);
|
||||
});
|
||||
|
||||
test("should return valid paths in absolute path mode", async () => {
|
||||
const files = ["a.txt", "b/", "b/c.txt"];
|
||||
addToTestDir(files);
|
||||
await expectPaths(
|
||||
[path.join(TEST_DIR, "a.txt"), path.join(TEST_DIR, "b", "c.txt")],
|
||||
[],
|
||||
{
|
||||
returnRelativePaths: false,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("should skip .git and node_modules folders", async () => {
|
||||
const files = [
|
||||
"a.txt",
|
||||
".git/",
|
||||
".git/config",
|
||||
".git/HEAD",
|
||||
".git/objects/",
|
||||
".git/objects/1234567890abcdef",
|
||||
"node_modules/",
|
||||
"node_modules/package/",
|
||||
"node_modules/package/index.js",
|
||||
"src/",
|
||||
"src/index.ts",
|
||||
];
|
||||
addToTestDir(files);
|
||||
await expectPaths(
|
||||
["a.txt", "src/index.ts"],
|
||||
[
|
||||
".git/config",
|
||||
".git/HEAD",
|
||||
"node_modules/package/index.js",
|
||||
".git/objects/1234567890abcdef",
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test("should walk continue repo without getting any files of the default ignore types", async () => {
|
||||
const results = await walkDir(path.join(__dirname, ".."), ide, {
|
||||
ignoreFiles: [".gitignore", ".continueignore"],
|
||||
expect(files.sort()).toEqual(
|
||||
[
|
||||
expect.stringContaining("src/file1.ts"),
|
||||
expect.stringContaining("src/file2.ts"),
|
||||
expect.stringContaining("src/nested/file3.ts"),
|
||||
].sort(),
|
||||
);
|
||||
});
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
expect(results.some((file) => file.includes("/node_modules/"))).toBe(false);
|
||||
expect(results.some((file) => file.includes("/.git/"))).toBe(false);
|
||||
expect(
|
||||
results.some(
|
||||
(file) =>
|
||||
file.endsWith(".gitignore") ||
|
||||
file.endsWith(".continueignore") ||
|
||||
file.endsWith("package-lock.json"),
|
||||
),
|
||||
).toBe(false);
|
||||
// At some point we will cross this number, but in case we leap past it suddenly I think we'd want to investigate why
|
||||
expect(results.length).toBeLessThan(1500);
|
||||
});
|
||||
|
||||
// This test is passing when this file is ran individually, but failing with `directory not found` error
|
||||
// when the full test suite is ran
|
||||
test.skip("should walk continue/extensions/vscode without getting any files in the .continueignore", async () => {
|
||||
const vscodePath = path.join(__dirname, "../..", "extensions", "vscode");
|
||||
const results = await walkDir(vscodePath, ide, {
|
||||
ignoreFiles: [".gitignore", ".continueignore"],
|
||||
it("should respect .gitignore", async () => {
|
||||
addToTestDir([
|
||||
["src/file1.ts", "content1"],
|
||||
["src/file2.ts", "content2"],
|
||||
"node_modules/",
|
||||
["node_modules/pkg/file.js", "ignored"],
|
||||
[".gitignore", "node_modules/"],
|
||||
]);
|
||||
|
||||
const files = await walkDir(
|
||||
(await testIde.getWorkspaceDirs())[0],
|
||||
testIde,
|
||||
);
|
||||
|
||||
expect(files).toEqual(
|
||||
expect.not.arrayContaining([
|
||||
expect.stringContaining("node_modules/pkg/file.js"),
|
||||
]),
|
||||
);
|
||||
expect(files.sort()).toEqual(
|
||||
[
|
||||
expect.stringContaining("src/file1.ts"),
|
||||
expect.stringContaining("src/file2.ts"),
|
||||
].sort(),
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle onlyDirs option", async () => {
|
||||
addToTestDir([
|
||||
"src/",
|
||||
["src/file1.ts", "content1"],
|
||||
"src/nested/",
|
||||
["src/nested/file2.ts", "content2"],
|
||||
]);
|
||||
|
||||
const dirs = await walkDir(
|
||||
(await testIde.getWorkspaceDirs())[0],
|
||||
testIde,
|
||||
{
|
||||
onlyDirs: true,
|
||||
},
|
||||
);
|
||||
|
||||
expect(dirs.sort()).toEqual(
|
||||
[
|
||||
expect.stringContaining("src"),
|
||||
expect.stringContaining("src/nested"),
|
||||
].sort(),
|
||||
);
|
||||
});
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
expect(results.some((file) => file.includes("/textmate-syntaxes/"))).toBe(
|
||||
false,
|
||||
);
|
||||
expect(results.some((file) => file.includes(".tmLanguage"))).toBe(false);
|
||||
});
|
||||
|
||||
// This test is passing when this file is ran individually, but failing with `jest not found` error
|
||||
// when the full test suite is ran
|
||||
test.skip("should perform the same number of dir reads as 1 + the number of dirs that contain files", async () => {
|
||||
const files = [
|
||||
"a.txt",
|
||||
"b.py",
|
||||
"c.ts",
|
||||
"d/",
|
||||
"d/e.txt",
|
||||
"d/f.py",
|
||||
"d/g/",
|
||||
"d/g/h.ts",
|
||||
"d/g/i/",
|
||||
"d/g/i/j.ts",
|
||||
];
|
||||
describe("walkDirAsync", () => {
|
||||
it("should yield files asynchronously", async () => {
|
||||
addToTestDir([
|
||||
"src/",
|
||||
["src/file1.ts", "content1"],
|
||||
["src/file2.ts", "content2"],
|
||||
]);
|
||||
|
||||
const numDirs = files.filter((file) => !file.includes(".")).length;
|
||||
const numDirsPlusTopLevelRead = numDirs + 1;
|
||||
const files: string[] = [];
|
||||
for await (const file of walkDirAsync(
|
||||
(await testIde.getWorkspaceDirs())[0],
|
||||
testIde,
|
||||
)) {
|
||||
files.push(file);
|
||||
}
|
||||
|
||||
addToTestDir(files);
|
||||
expect(files.sort()).toEqual(
|
||||
[
|
||||
expect.stringContaining("src/file1.ts"),
|
||||
expect.stringContaining("src/file2.ts"),
|
||||
].sort(),
|
||||
);
|
||||
});
|
||||
|
||||
const mockListDir = jest.spyOn(ide, "listDir");
|
||||
it("should handle relative paths option", async () => {
|
||||
addToTestDir([
|
||||
"src/",
|
||||
["src/file1.ts", "content1"],
|
||||
["src/file2.ts", "content2"],
|
||||
]);
|
||||
|
||||
await walkTestDir();
|
||||
const files: string[] = [];
|
||||
for await (const file of walkDirAsync(
|
||||
(await testIde.getWorkspaceDirs())[0],
|
||||
testIde,
|
||||
{
|
||||
returnRelativeUrisPaths: true,
|
||||
},
|
||||
)) {
|
||||
files.push(file);
|
||||
}
|
||||
|
||||
expect(mockListDir).toHaveBeenCalledTimes(numDirsPlusTopLevelRead);
|
||||
expect(files.sort()).toEqual(["src/file1.ts", "src/file2.ts"].sort());
|
||||
});
|
||||
});
|
||||
|
||||
describe("walkDirs", () => {
|
||||
it("should walk multiple workspace directories", async () => {
|
||||
addToTestDir([
|
||||
"workspace1/src/",
|
||||
["workspace1/src/file1.ts", "content1"],
|
||||
"workspace2/src/",
|
||||
["workspace2/src/file2.ts", "content2"],
|
||||
]);
|
||||
|
||||
const files = await walkDirs(testIde, undefined, [
|
||||
(await testIde.getWorkspaceDirs())[0] + "/workspace1",
|
||||
(await testIde.getWorkspaceDirs())[0] + "/workspace2", // Second workspace dir
|
||||
]);
|
||||
|
||||
expect(files).toContainEqual(expect.stringContaining("file1.ts"));
|
||||
expect(files).toContainEqual(expect.stringContaining("file2.ts"));
|
||||
});
|
||||
|
||||
it("should handle empty directories", async () => {
|
||||
addToTestDir(["empty/"]);
|
||||
|
||||
const files = await walkDirs(testIde);
|
||||
console.log("EMPTY DIR", files);
|
||||
|
||||
expect(files).toEqual([]);
|
||||
});
|
||||
|
||||
it("should skip symlinks", async () => {
|
||||
const filePath = path.join(TEST_DIR_PATH, "real.ts");
|
||||
addToTestDir([["real.ts", "content"]]);
|
||||
fs.symlink(
|
||||
filePath,
|
||||
path.join(TEST_DIR_PATH, "symlink.ts"),
|
||||
"file",
|
||||
() => {},
|
||||
);
|
||||
|
||||
const files = await walkDirs(testIde);
|
||||
|
||||
expect(files).not.toContainEqual(expect.stringContaining("symlink.ts"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("walkDir ignore patterns", () => {
|
||||
it("should handle negation patterns in gitignore", async () => {
|
||||
addToTestDir([
|
||||
[".gitignore", "**/*\n!*.py"],
|
||||
["a.txt", "content"],
|
||||
["b.py", "content"],
|
||||
["c.ts", "content"],
|
||||
]);
|
||||
|
||||
const files = await walkDir(
|
||||
(await testIde.getWorkspaceDirs())[0],
|
||||
testIde,
|
||||
{
|
||||
returnRelativeUrisPaths: true,
|
||||
},
|
||||
);
|
||||
|
||||
expect(files).toContain("b.py");
|
||||
expect(files).not.toContain("a.txt");
|
||||
expect(files).not.toContain("c.ts");
|
||||
});
|
||||
|
||||
it("should handle leading slash patterns", async () => {
|
||||
addToTestDir([
|
||||
[".gitignore", "/no.txt"],
|
||||
["no.txt", "content"],
|
||||
"sub/",
|
||||
["sub/no.txt", "content"],
|
||||
["a.txt", "content"],
|
||||
]);
|
||||
|
||||
const files = await walkDir(
|
||||
(await testIde.getWorkspaceDirs())[0],
|
||||
testIde,
|
||||
{
|
||||
returnRelativeUrisPaths: true,
|
||||
},
|
||||
);
|
||||
|
||||
expect(files).not.toContain("no.txt");
|
||||
expect(files).toContain("sub/no.txt");
|
||||
expect(files).toContain("a.txt");
|
||||
});
|
||||
|
||||
it("should handle multiple gitignore files in nested structure", async () => {
|
||||
addToTestDir([
|
||||
[".gitignore", "*.txt"],
|
||||
["a.py", "content"],
|
||||
["b.txt", "content"],
|
||||
"c/",
|
||||
["c/.gitignore", "*.py"],
|
||||
["c/d.txt", "content"],
|
||||
["c/e.py", "content"],
|
||||
]);
|
||||
|
||||
const files = await walkDir(
|
||||
(await testIde.getWorkspaceDirs())[0],
|
||||
testIde,
|
||||
{
|
||||
returnRelativeUrisPaths: true,
|
||||
},
|
||||
);
|
||||
|
||||
expect(files).toContain("a.py");
|
||||
expect(files).not.toContain("b.txt");
|
||||
expect(files).not.toContain("c/d.txt");
|
||||
expect(files).not.toContain("c/e.py");
|
||||
});
|
||||
|
||||
it("should handle both gitignore and continueignore", async () => {
|
||||
addToTestDir([
|
||||
[".gitignore", "*.py"],
|
||||
[".continueignore", "*.ts"],
|
||||
["a.txt", "content"],
|
||||
["b.py", "content"],
|
||||
["c.ts", "content"],
|
||||
["d.js", "content"],
|
||||
]);
|
||||
|
||||
const files = await walkDir(
|
||||
(await testIde.getWorkspaceDirs())[0],
|
||||
testIde,
|
||||
{
|
||||
returnRelativeUrisPaths: true,
|
||||
},
|
||||
);
|
||||
|
||||
expect(files).toContain("a.txt");
|
||||
expect(files).toContain("d.js");
|
||||
expect(files).not.toContain("b.py");
|
||||
expect(files).not.toContain("c.ts");
|
||||
});
|
||||
|
||||
it("should handle complex wildcard patterns", async () => {
|
||||
addToTestDir([
|
||||
[".gitignore", "*.what\n!important.what\ntemp/\n/root_only.txt"],
|
||||
["a.what", "content"],
|
||||
["important.what", "content"],
|
||||
["root_only.txt", "content"],
|
||||
"subdir/",
|
||||
["subdir/root_only.txt", "content"],
|
||||
["subdir/b.what", "content"],
|
||||
"temp/",
|
||||
["temp/c.txt", "content"],
|
||||
]);
|
||||
|
||||
const files = await walkDir(
|
||||
(await testIde.getWorkspaceDirs())[0],
|
||||
testIde,
|
||||
{
|
||||
returnRelativeUrisPaths: true,
|
||||
},
|
||||
);
|
||||
|
||||
expect(files).toContain("important.what");
|
||||
expect(files).toContain("subdir/root_only.txt");
|
||||
expect(files).not.toContain("a.what");
|
||||
expect(files).not.toContain("root_only.txt");
|
||||
expect(files).not.toContain("subdir/b.what");
|
||||
expect(files).not.toContain("temp/c.txt");
|
||||
});
|
||||
|
||||
it("should skip common system directories by default", async () => {
|
||||
addToTestDir([
|
||||
["normal/file.txt", "content"],
|
||||
[".git/config", "content"],
|
||||
["node_modules/package/index.js", "content"],
|
||||
["dist/bundle.js", "content"],
|
||||
["coverage/lcov.env", "content"],
|
||||
]);
|
||||
|
||||
const files = await walkDir(
|
||||
(await testIde.getWorkspaceDirs())[0],
|
||||
testIde,
|
||||
{
|
||||
returnRelativeUrisPaths: true,
|
||||
},
|
||||
);
|
||||
|
||||
expect(files).toContain("normal/file.txt");
|
||||
expect(files).not.toContain(".git/config");
|
||||
expect(files).not.toContain("node_modules/package/index.js");
|
||||
expect(files).not.toContain("coverage/lcov.info");
|
||||
});
|
||||
|
||||
it("should handle directory-specific ignore patterns correctly", async () => {
|
||||
addToTestDir([
|
||||
[".gitignore", "/abc"],
|
||||
["abc", "content"],
|
||||
"xyz/",
|
||||
["xyz/.gitignore", "xyz"],
|
||||
["xyz/abc", "content"],
|
||||
["xyz/xyz", "content"],
|
||||
["xyz/normal.txt", "content"],
|
||||
]);
|
||||
|
||||
const files = await walkDir(
|
||||
(await testIde.getWorkspaceDirs())[0],
|
||||
testIde,
|
||||
{
|
||||
returnRelativeUrisPaths: true,
|
||||
},
|
||||
);
|
||||
|
||||
expect(files).not.toContain("abc");
|
||||
expect(files).toContain("xyz/abc");
|
||||
expect(files).not.toContain("xyz/xyz");
|
||||
expect(files).toContain("xyz/normal.txt");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,8 +1,6 @@
|
|||
import path from "node:path";
|
||||
|
||||
import ignore, { Ignore } from "ignore";
|
||||
|
||||
import { FileType, IDE } from "../index.d.js";
|
||||
import type { FileType, IDE } from "..";
|
||||
|
||||
import {
|
||||
DEFAULT_IGNORE_DIRS,
|
||||
|
|
@ -11,12 +9,13 @@ import {
|
|||
defaultIgnoreFile,
|
||||
getGlobalContinueIgArray,
|
||||
gitIgArrayFromFile,
|
||||
} from "./ignore.js";
|
||||
} from "./ignore";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
|
||||
export interface WalkerOptions {
|
||||
ignoreFiles?: string[];
|
||||
onlyDirs?: boolean;
|
||||
returnRelativePaths?: boolean;
|
||||
returnRelativeUrisPaths?: boolean;
|
||||
additionalIgnoreRules?: string[];
|
||||
}
|
||||
|
||||
|
|
@ -24,8 +23,8 @@ type Entry = [string, FileType];
|
|||
|
||||
// helper struct used for the DFS walk
|
||||
type WalkableEntry = {
|
||||
relPath: string;
|
||||
absPath: string;
|
||||
relativeUriPath: string;
|
||||
uri: string;
|
||||
type: FileType;
|
||||
entry: Entry;
|
||||
};
|
||||
|
|
@ -45,7 +44,7 @@ class DFSWalker {
|
|||
private readonly ignoreFileNames: Set<string>;
|
||||
|
||||
constructor(
|
||||
private readonly path: string,
|
||||
private readonly uri: string,
|
||||
private readonly ide: IDE,
|
||||
private readonly options: WalkerOptions,
|
||||
) {
|
||||
|
|
@ -54,10 +53,6 @@ class DFSWalker {
|
|||
|
||||
// walk is a depth-first search implementation
|
||||
public async *walk(): AsyncGenerator<string> {
|
||||
const fixupFunc = await this.newPathFixupFunc(
|
||||
this.options.returnRelativePaths ? "" : this.path,
|
||||
this.ide,
|
||||
);
|
||||
const root = this.newRootWalkContext();
|
||||
const stack = [root];
|
||||
for (let cur = stack.pop(); cur; cur = stack.pop()) {
|
||||
|
|
@ -77,10 +72,19 @@ class DFSWalker {
|
|||
});
|
||||
if (this.options.onlyDirs) {
|
||||
// when onlyDirs is enabled the walker will only return directory names
|
||||
yield fixupFunc(w.relPath);
|
||||
if (this.options.returnRelativeUrisPaths) {
|
||||
yield w.relativeUriPath;
|
||||
} else {
|
||||
yield w.uri;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
yield fixupFunc(w.relPath);
|
||||
// Note that shouldInclude handles skipping files if options.onlyDirs is true
|
||||
if (this.options.returnRelativeUrisPaths) {
|
||||
yield w.relativeUriPath;
|
||||
} else {
|
||||
yield w.uri;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -90,14 +94,17 @@ class DFSWalker {
|
|||
const globalIgnoreFile = getGlobalContinueIgArray();
|
||||
return {
|
||||
walkableEntry: {
|
||||
relPath: "",
|
||||
absPath: this.path,
|
||||
relativeUriPath: "",
|
||||
uri: this.uri,
|
||||
type: 2 as FileType.Directory,
|
||||
entry: ["", 2 as FileType.Directory],
|
||||
},
|
||||
ignoreContexts: [
|
||||
{
|
||||
ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile).add(globalIgnoreFile),
|
||||
ignore: ignore()
|
||||
.add(defaultIgnoreDir)
|
||||
.add(defaultIgnoreFile)
|
||||
.add(globalIgnoreFile),
|
||||
dirname: "",
|
||||
},
|
||||
],
|
||||
|
|
@ -107,15 +114,13 @@ class DFSWalker {
|
|||
private async listDirForWalking(
|
||||
walkableEntry: WalkableEntry,
|
||||
): Promise<WalkableEntry[]> {
|
||||
const entries = await this.ide.listDir(walkableEntry.absPath);
|
||||
return entries.map((e) => {
|
||||
return {
|
||||
relPath: path.join(walkableEntry.relPath, e[0]),
|
||||
absPath: path.join(walkableEntry.absPath, e[0]),
|
||||
type: e[1],
|
||||
entry: e,
|
||||
};
|
||||
});
|
||||
const entries = await this.ide.listDir(walkableEntry.uri);
|
||||
return entries.map((e) => ({
|
||||
relativeUriPath: `${walkableEntry.relativeUriPath}${walkableEntry.relativeUriPath ? "/" : ""}${e[0]}`,
|
||||
uri: joinPathsToUri(walkableEntry.uri, e[0]),
|
||||
type: e[1],
|
||||
entry: e,
|
||||
}));
|
||||
}
|
||||
|
||||
private async getIgnoreToApplyInDir(
|
||||
|
|
@ -129,35 +134,32 @@ class DFSWalker {
|
|||
const patterns = ignoreFilesInDir.map((c) => gitIgArrayFromFile(c)).flat();
|
||||
const newIgnoreContext = {
|
||||
ignore: ignore().add(patterns),
|
||||
dirname: curDir.walkableEntry.relPath,
|
||||
dirname: curDir.walkableEntry.relativeUriPath,
|
||||
};
|
||||
return [...curDir.ignoreContexts, newIgnoreContext];
|
||||
}
|
||||
|
||||
private async loadIgnoreFiles(entries: WalkableEntry[]): Promise<string[]> {
|
||||
const ignoreEntries = entries.filter((w) => this.isIgnoreFile(w.entry));
|
||||
const ignoreEntries = entries.filter((w) =>
|
||||
this.entryIsIgnoreFile(w.entry),
|
||||
);
|
||||
const promises = ignoreEntries.map(async (w) => {
|
||||
return await this.ide.readFile(w.absPath);
|
||||
return await this.ide.readFile(w.uri);
|
||||
});
|
||||
return Promise.all(promises);
|
||||
}
|
||||
|
||||
private isIgnoreFile(e: Entry): boolean {
|
||||
const p = e[0];
|
||||
return this.ignoreFileNames.has(p);
|
||||
}
|
||||
|
||||
private shouldInclude(
|
||||
walkableEntry: WalkableEntry,
|
||||
ignoreContexts: IgnoreContext[],
|
||||
) {
|
||||
if (this.entryIsSymlink(walkableEntry.entry)) {
|
||||
// If called from the root, a symlink either links to a real file in this repository,
|
||||
// and therefore will be walked OR it linksto something outside of the repository and
|
||||
// and therefore will be walked OR it links to something outside of the repository and
|
||||
// we do not want to index it
|
||||
return false;
|
||||
}
|
||||
let relPath = walkableEntry.relPath;
|
||||
let relPath = walkableEntry.relativeUriPath;
|
||||
if (this.entryIsDirectory(walkableEntry.entry)) {
|
||||
relPath = `${relPath}/`;
|
||||
} else {
|
||||
|
|
@ -166,7 +168,7 @@ class DFSWalker {
|
|||
}
|
||||
}
|
||||
for (const ig of ignoreContexts) {
|
||||
// remove the directory name and path seperator from the match path, unless this an ignore file
|
||||
// remove the directory name and path separator from the match path, unless this an ignore file
|
||||
// in the root directory
|
||||
const prefixLength = ig.dirname.length === 0 ? 0 : ig.dirname.length + 1;
|
||||
// The ignore library expects a path relative to the ignore file location
|
||||
|
|
@ -186,50 +188,53 @@ class DFSWalker {
|
|||
return entry[1] === (64 as FileType.SymbolicLink);
|
||||
}
|
||||
|
||||
// returns a function which will optionally prefix a root path and fixup the paths for the appropriate OS filesystem (i.e. windows)
|
||||
// the reason to construct this function once is to avoid the need to call ide.pathSep() multiple times
|
||||
private async newPathFixupFunc(
|
||||
rootPath: string,
|
||||
ide: IDE,
|
||||
): Promise<(relPath: string) => string> {
|
||||
const pathSep = await ide.pathSep();
|
||||
const prefix = rootPath === "" ? "" : rootPath + pathSep;
|
||||
if (pathSep === "/") {
|
||||
if (rootPath === "") {
|
||||
// return a no-op function in this case to avoid unnecessary string concatentation
|
||||
return (relPath: string) => relPath;
|
||||
}
|
||||
return (relPath: string) => prefix + relPath;
|
||||
private entryIsIgnoreFile(e: Entry): boolean {
|
||||
if (
|
||||
e[1] === (2 as FileType.Directory) ||
|
||||
e[1] === (64 as FileType.SymbolicLink)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
// this serves to 'fix-up' the path on Windows
|
||||
return (relPath: string) => {
|
||||
return prefix + relPath.split("/").join(pathSep);
|
||||
};
|
||||
return this.ignoreFileNames.has(e[0]);
|
||||
}
|
||||
}
|
||||
|
||||
const defaultOptions: WalkerOptions = {
|
||||
ignoreFiles: [".gitignore", ".continueignore"],
|
||||
additionalIgnoreRules: [...DEFAULT_IGNORE_DIRS, ...DEFAULT_IGNORE_FILETYPES],
|
||||
onlyDirs: false,
|
||||
returnRelativeUrisPaths: false,
|
||||
};
|
||||
|
||||
export async function walkDir(
|
||||
path: string,
|
||||
uri: string,
|
||||
ide: IDE,
|
||||
_options?: WalkerOptions,
|
||||
_optionOverrides?: WalkerOptions,
|
||||
): Promise<string[]> {
|
||||
let paths: string[] = [];
|
||||
for await (const p of walkDirAsync(path, ide, _options)) {
|
||||
paths.push(p);
|
||||
let urisOrRelativePaths: string[] = [];
|
||||
for await (const p of walkDirAsync(uri, ide, _optionOverrides)) {
|
||||
urisOrRelativePaths.push(p);
|
||||
}
|
||||
return paths;
|
||||
return urisOrRelativePaths;
|
||||
}
|
||||
|
||||
export async function* walkDirAsync(
|
||||
path: string,
|
||||
ide: IDE,
|
||||
_options?: WalkerOptions,
|
||||
_optionOverrides?: WalkerOptions,
|
||||
): AsyncGenerator<string> {
|
||||
const options = { ...defaultOptions, ..._options };
|
||||
const options = { ...defaultOptions, ..._optionOverrides };
|
||||
yield* new DFSWalker(path, ide, options).walk();
|
||||
}
|
||||
|
||||
export async function walkDirs(
|
||||
ide: IDE,
|
||||
_optionOverrides?: WalkerOptions,
|
||||
dirs?: string[], // Can pass dirs to prevent duplicate calls
|
||||
): Promise<string[]> {
|
||||
const workspaceDirs = dirs ?? (await ide.getWorkspaceDirs());
|
||||
const results = await Promise.all(
|
||||
workspaceDirs.map((dir) => walkDir(dir, ide, _optionOverrides)),
|
||||
);
|
||||
return results.flat();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,17 +9,27 @@ class Asksage extends BaseLLM {
|
|||
};
|
||||
|
||||
private static modelConversion: { [key: string]: string } = {
|
||||
"gpt-4o": "gpt-4o",
|
||||
"gpt-4o-mini": "gpt-4o-mini",
|
||||
"gpt4-gov": "gpt4-gov",
|
||||
"gpt-4o-gov": "gpt-4o-gov",
|
||||
"gpt-3.5-turbo": "gpt35-16k",
|
||||
"mistral-large-latest": "mistral-large",
|
||||
"llama3-70b": "llma3",
|
||||
"gemini-1.5-pro-latest": "google-gemini-pro",
|
||||
"claude-3-5-sonnet-20240620": "claude-35-sonnet",
|
||||
"claude-3-opus-20240229": "claude-3-opus",
|
||||
"claude-3-sonnet-20240229": "claude-3-sonnet",
|
||||
"gpt-4o-gov": "gpt-4o-gov", // Works
|
||||
"gpt-4o-mini-gov": "gpt-4o-mini-gov",
|
||||
"gpt4-gov": "gpt4-gov", // Works
|
||||
"gpt-gov": "gpt-gov", // Works
|
||||
"gpt-4o": "gpt-4o", // Works
|
||||
"gpt-4o-mini": "gpt-4o-mini", // Works
|
||||
"gpt4": "gpt4", // Works
|
||||
"gpt4-32k": "gpt4-32k",
|
||||
"gpt-o1": "gpt-o1", // Works
|
||||
"gpt-o1-mini": "gpt-o1-mini", // Works
|
||||
"gpt-3.5-turbo": "gpt35-16k", // Works
|
||||
"aws-bedrock-claude-35-sonnet-gov": "aws-bedrock-claude-35-sonnet-gov", // Works
|
||||
"claude-3-5-sonnet-latest": "claude-35-sonnet", // Works
|
||||
"claude-3-opus-20240229": "claude-3-opus", // Works
|
||||
"claude-3-sonnet-20240229": "claude-3-sonnet", // Works
|
||||
"grok-beta": "xai-grok",
|
||||
"groq-llama33": "groq-llama33",
|
||||
"groq-70b": "groq-70b",
|
||||
"mistral-large-latest": "mistral-large", // Works
|
||||
"llama3-70b": "llma3", // Works
|
||||
"gemini-1.5-pro-latest": "google-gemini-pro", // Works
|
||||
};
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
|
|
@ -28,7 +38,10 @@ class Asksage extends BaseLLM {
|
|||
}
|
||||
|
||||
protected _convertModelName(model: string): string {
|
||||
return Asksage.modelConversion[model] ?? model;
|
||||
console.log("Converting model:", model);
|
||||
const convertedModel = Asksage.modelConversion[model] ?? model;
|
||||
console.log("Converted model:", convertedModel);
|
||||
return convertedModel;
|
||||
}
|
||||
|
||||
protected _convertMessage(message: ChatMessage) {
|
||||
|
|
|
|||
|
|
@ -152,6 +152,12 @@ class Ollama extends BaseLLM {
|
|||
"llama3.2-90b": "llama3.2:90b",
|
||||
"phi-2": "phi:2.7b",
|
||||
"phind-codellama-34b": "phind-codellama:34b-v2",
|
||||
"qwen2.5-coder-0.5b": "qwen2.5-coder:0.5b",
|
||||
"qwen2.5-coder-1.5b": "qwen2.5-coder:1.5b",
|
||||
"qwen2.5-coder-3b": "qwen2.5-coder:3b",
|
||||
"qwen2.5-coder-7b": "qwen2.5-coder:7b",
|
||||
"qwen2.5-coder-14b": "qwen2.5-coder:14b",
|
||||
"qwen2.5-coder-32b": "qwen2.5-coder:32b",
|
||||
"wizardcoder-7b": "wizardcoder:7b-python",
|
||||
"wizardcoder-13b": "wizardcoder:13b-python",
|
||||
"wizardcoder-34b": "wizardcoder:34b-python",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { Chunk } from "../../index.js";
|
||||
import { getBasename } from "../../util/index.js";
|
||||
import { getUriPathBasename } from "../../util/uri.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
const RERANK_PROMPT = (
|
||||
|
|
@ -47,7 +47,7 @@ export class LLMReranker extends BaseLLM {
|
|||
|
||||
async scoreChunk(chunk: Chunk, query: string): Promise<number> {
|
||||
const completion = await this.complete(
|
||||
RERANK_PROMPT(query, getBasename(chunk.filepath), chunk.content),
|
||||
RERANK_PROMPT(query, getUriPathBasename(chunk.filepath), chunk.content),
|
||||
new AbortController().signal,
|
||||
{
|
||||
maxTokens: 1,
|
||||
|
|
|
|||
|
|
@ -1,59 +0,0 @@
|
|||
import path from "path";
|
||||
|
||||
import { IDE } from "../..";
|
||||
|
||||
import { DEFAULT_PROMPTS_FOLDER } from ".";
|
||||
|
||||
const DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
|
||||
# It is used to define and reuse prompts within Continue
|
||||
# Continue will automatically create a slash command for each prompt in the .prompts folder
|
||||
# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files
|
||||
temperature: 0.0
|
||||
---
|
||||
{{{ diff }}}
|
||||
|
||||
Give me feedback on the above changes. For each file, you should output a markdown section including the following:
|
||||
- If you found any problems, an h3 like "❌ <filename>"
|
||||
- If you didn't find any problems, an h3 like "✅ <filename>"
|
||||
- If you found any problems, add below a bullet point description of what you found, including a minimal code snippet explaining how to fix it
|
||||
- If you didn't find any problems, you don't need to add anything else
|
||||
|
||||
Here is an example. The example is surrounded in backticks, but your response should not be:
|
||||
|
||||
\`\`\`
|
||||
### ✅ <Filename1>
|
||||
|
||||
### ❌ <Filename2>
|
||||
|
||||
<Description>
|
||||
\`\`\`
|
||||
|
||||
You should look primarily for the following types of issues, and only mention other problems if they are highly pressing.
|
||||
|
||||
- console.logs that have been left after debugging
|
||||
- repeated code
|
||||
- algorithmic errors that could fail under edge cases
|
||||
- something that could be refactored
|
||||
|
||||
Make sure to review ALL files that were changed, do not skip any.
|
||||
`;
|
||||
|
||||
export async function createNewPromptFile(
|
||||
ide: IDE,
|
||||
promptPath: string | undefined,
|
||||
): Promise<void> {
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
if (workspaceDirs.length === 0) {
|
||||
throw new Error(
|
||||
"No workspace directories found. Make sure you've opened a folder in your IDE.",
|
||||
);
|
||||
}
|
||||
const promptFilePath = path.join(
|
||||
workspaceDirs[0],
|
||||
promptPath ?? DEFAULT_PROMPTS_FOLDER,
|
||||
"new-prompt-file.prompt",
|
||||
);
|
||||
|
||||
await ide.writeFile(promptFilePath, DEFAULT_PROMPT_FILE);
|
||||
await ide.openFile(promptFilePath);
|
||||
}
|
||||
|
|
@ -1,9 +1,20 @@
|
|||
import Handlebars from "handlebars";
|
||||
import { ContextItem, ContinueSDK, IContextProvider } from "../..";
|
||||
|
||||
function createContextItem(item: ContextItem, provider: IContextProvider) {
|
||||
return {
|
||||
...item,
|
||||
id: {
|
||||
itemId: item.description,
|
||||
providerTitle: provider.description.title,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function getContextProviderHelpers(
|
||||
context: any,
|
||||
context: ContinueSDK,
|
||||
): Array<[string, Handlebars.HelperDelegate]> | undefined {
|
||||
return context.config.contextProviders?.map((provider: any) => [
|
||||
return context.config.contextProviders?.map((provider: IContextProvider) => [
|
||||
provider.description.title,
|
||||
async (helperContext: any) => {
|
||||
const items = await provider.getContextItems(helperContext, {
|
||||
|
|
@ -17,21 +28,11 @@ export function getContextProviderHelpers(
|
|||
selectedCode: context.selectedCode,
|
||||
});
|
||||
|
||||
items.forEach((item: any) =>
|
||||
items.forEach((item) =>
|
||||
context.addContextItem(createContextItem(item, provider)),
|
||||
);
|
||||
|
||||
return items.map((item: any) => item.content).join("\n\n");
|
||||
return items.map((item) => item.content).join("\n\n");
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function createContextItem(item: any, provider: any) {
|
||||
return {
|
||||
...item,
|
||||
id: {
|
||||
itemId: item.description,
|
||||
providerTitle: provider.description.title,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,25 +0,0 @@
|
|||
import { IDE } from "../..";
|
||||
import { walkDir } from "../../indexing/walkDir";
|
||||
|
||||
export async function getPromptFiles(
|
||||
ide: IDE,
|
||||
dir: string,
|
||||
): Promise<{ path: string; content: string }[]> {
|
||||
try {
|
||||
const exists = await ide.fileExists(dir);
|
||||
|
||||
if (!exists) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const paths = await walkDir(dir, ide, { ignoreFiles: [] });
|
||||
const results = paths.map(async (path) => {
|
||||
const content = await ide.readFile(path); // make a try catch
|
||||
return { path, content };
|
||||
});
|
||||
return Promise.all(results);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import Handlebars from "handlebars";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
export function convertToLetter(num: number): string {
|
||||
function convertToLetter(num: number): string {
|
||||
let result = "";
|
||||
while (num > 0) {
|
||||
const remainder = (num - 1) % 26;
|
||||
|
|
@ -15,7 +15,7 @@ export function convertToLetter(num: number): string {
|
|||
* We replace filepaths with alphabetic characters to handle
|
||||
* escaping issues.
|
||||
*/
|
||||
export const replaceFilepaths = (
|
||||
const replaceFilepaths = (
|
||||
value: string,
|
||||
ctxProviderNames: string[],
|
||||
): [string, { [key: string]: string }] => {
|
||||
|
|
@ -95,7 +95,10 @@ export async function prepareTemplateAndData(
|
|||
return [newTemplate, data];
|
||||
}
|
||||
|
||||
export function compileAndRenderTemplate(template: string, data: Record<string, string>): string {
|
||||
export function compileAndRenderTemplate(
|
||||
template: string,
|
||||
data: Record<string, string>,
|
||||
): string {
|
||||
const templateFn = Handlebars.compile(template);
|
||||
return templateFn(data);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1 @@
|
|||
import { createNewPromptFile } from "./createNewPromptFile";
|
||||
import { getPromptFiles } from "./getPromptFiles";
|
||||
import { slashCommandFromPromptFile } from "./slashCommandFromPromptFile";
|
||||
|
||||
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
|
||||
|
||||
export { createNewPromptFile, getPromptFiles, slashCommandFromPromptFile };
|
||||
export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts";
|
||||
|
|
|
|||
|
|
@ -1,35 +1,14 @@
|
|||
import * as YAML from "yaml";
|
||||
|
||||
import { ContinueSDK, SlashCommand } from "../..";
|
||||
import { getBasename } from "../../util/index";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
import { getLastNPathParts } from "../../util/uri";
|
||||
import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2";
|
||||
|
||||
import { getContextProviderHelpers } from "./getContextProviderHelpers";
|
||||
import { renderTemplatedString } from "./renderTemplatedString";
|
||||
import { updateChatHistory } from "./updateChatHistory";
|
||||
|
||||
export function extractName(preamble: { name?: string }, path: string): string {
|
||||
return preamble.name ?? getBasename(path).split(".prompt")[0];
|
||||
}
|
||||
|
||||
export function parsePromptFile(path: string, content: string) {
|
||||
let [preambleRaw, prompt] = content.split("\n---\n");
|
||||
if (prompt === undefined) {
|
||||
prompt = preambleRaw;
|
||||
preambleRaw = "";
|
||||
}
|
||||
|
||||
const preamble = YAML.parse(preambleRaw) ?? {};
|
||||
const name = extractName(preamble, path);
|
||||
const description = preamble.description ?? name;
|
||||
|
||||
let systemMessage: string | undefined = undefined;
|
||||
if (prompt.includes("<system>")) {
|
||||
systemMessage = prompt.split("<system>")[1].split("</system>")[0].trim();
|
||||
prompt = prompt.split("</system>")[1].trim();
|
||||
}
|
||||
|
||||
return { name, description, systemMessage, prompt };
|
||||
return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
|
||||
}
|
||||
|
||||
export function extractUserInput(input: string, commandName: string): string {
|
||||
|
|
@ -39,26 +18,23 @@ export function extractUserInput(input: string, commandName: string): string {
|
|||
return input;
|
||||
}
|
||||
|
||||
export async function getDefaultVariables(
|
||||
context: ContinueSDK,
|
||||
userInput: string,
|
||||
): Promise<Record<string, string>> {
|
||||
const currentFile = await context.ide.getCurrentFile();
|
||||
const vars: Record<string, string> = { input: userInput };
|
||||
if (currentFile) {
|
||||
vars.currentFile = currentFile.path;
|
||||
}
|
||||
return vars;
|
||||
}
|
||||
|
||||
export async function renderPrompt(
|
||||
async function renderPromptV1(
|
||||
prompt: string,
|
||||
context: ContinueSDK,
|
||||
userInput: string,
|
||||
) {
|
||||
const helpers = getContextProviderHelpers(context);
|
||||
|
||||
const inputData = await getDefaultVariables(context, userInput);
|
||||
// A few context providers that don't need to be in config.json to work in .prompt files
|
||||
const diff = await context.ide.getDiff(true);
|
||||
const currentFile = await context.ide.getCurrentFile();
|
||||
const inputData: Record<string, string> = {
|
||||
diff: diff.join("\n"),
|
||||
input: userInput,
|
||||
};
|
||||
if (currentFile) {
|
||||
inputData.currentFile = currentFile.path;
|
||||
}
|
||||
|
||||
return renderTemplatedString(
|
||||
prompt,
|
||||
|
|
@ -68,21 +44,26 @@ export async function renderPrompt(
|
|||
);
|
||||
}
|
||||
|
||||
export function slashCommandFromPromptFile(
|
||||
export function slashCommandFromPromptFileV1(
|
||||
path: string,
|
||||
content: string,
|
||||
): SlashCommand {
|
||||
const { name, description, systemMessage, prompt } = parsePromptFile(
|
||||
path,
|
||||
content,
|
||||
);
|
||||
): SlashCommand | null {
|
||||
const { name, description, systemMessage, prompt, version } =
|
||||
parsePromptFileV1V2(path, content);
|
||||
|
||||
if (version !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
run: async function* (context) {
|
||||
const originalSystemMessage = context.llm.systemMessage;
|
||||
context.llm.systemMessage = systemMessage;
|
||||
|
||||
const userInput = extractUserInput(context.input, name);
|
||||
const renderedPrompt = await renderPrompt(prompt, context, userInput);
|
||||
const renderedPrompt = await renderPromptV1(prompt, context, userInput);
|
||||
const messages = updateChatHistory(
|
||||
context.history,
|
||||
name,
|
||||
|
|
@ -96,6 +77,8 @@ export function slashCommandFromPromptFile(
|
|||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
|
||||
context.llm.systemMessage = originalSystemMessage;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { IDE } from "../..";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
import { getPathModuleForIde } from "../../util/pathModule";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
|
||||
const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
|
||||
# It is used to define and reuse prompts within Continue
|
||||
|
|
@ -45,24 +45,23 @@ export async function createNewPromptFileV2(
|
|||
"No workspace directories found. Make sure you've opened a folder in your IDE.",
|
||||
);
|
||||
}
|
||||
const pathModule = await getPathModuleForIde(ide);
|
||||
|
||||
const baseDir = pathModule.join(
|
||||
const baseDirUri = joinPathsToUri(
|
||||
workspaceDirs[0],
|
||||
promptPath ?? pathModule.join(".continue", "prompts"),
|
||||
promptPath ?? ".continue/prompts",
|
||||
);
|
||||
|
||||
// Find the first available filename
|
||||
let counter = 0;
|
||||
let promptFilePath: string;
|
||||
let promptFileUri: string;
|
||||
do {
|
||||
const suffix = counter === 0 ? "" : `-${counter}`;
|
||||
promptFilePath = pathModule.join(
|
||||
baseDir,
|
||||
promptFileUri = joinPathsToUri(
|
||||
baseDirUri,
|
||||
`new-prompt-file${suffix}.prompt`,
|
||||
);
|
||||
counter++;
|
||||
} while (await ide.fileExists(promptFilePath));
|
||||
} while (await ide.fileExists(promptFileUri));
|
||||
|
||||
const globalContext = new GlobalContext();
|
||||
const PROMPT_FILE =
|
||||
|
|
@ -72,6 +71,6 @@ export async function createNewPromptFileV2(
|
|||
|
||||
globalContext.update("hasAlreadyCreatedAPromptFile", true);
|
||||
|
||||
await ide.writeFile(promptFilePath, PROMPT_FILE);
|
||||
await ide.openFile(promptFilePath);
|
||||
await ide.writeFile(promptFileUri, PROMPT_FILE);
|
||||
await ide.openFile(promptFileUri);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
import { IDE } from "../..";
|
||||
import { walkDir } from "../../indexing/walkDir";
|
||||
import { getPathModuleForIde } from "../../util/pathModule";
|
||||
import { readAllGlobalPromptFiles } from "../../util/paths";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
import { DEFAULT_PROMPTS_FOLDER_V1 } from "../v1";
|
||||
|
||||
async function getPromptFilesFromDir(
|
||||
export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
|
||||
export async function getPromptFilesFromDir(
|
||||
ide: IDE,
|
||||
dir: string,
|
||||
): Promise<{ path: string; content: string }[]> {
|
||||
|
|
@ -15,7 +17,8 @@ async function getPromptFilesFromDir(
|
|||
}
|
||||
|
||||
const paths = await walkDir(dir, ide, { ignoreFiles: [] });
|
||||
const results = paths.map(async (path) => {
|
||||
const promptFilePaths = paths.filter((p) => p.endsWith(".prompt"));
|
||||
const results = promptFilePaths.map(async (path) => {
|
||||
const content = await ide.readFile(path); // make a try catch
|
||||
return { path, content };
|
||||
});
|
||||
|
|
@ -26,29 +29,29 @@ async function getPromptFilesFromDir(
|
|||
}
|
||||
}
|
||||
|
||||
export async function getAllPromptFilesV2(
|
||||
export async function getAllPromptFiles(
|
||||
ide: IDE,
|
||||
overridePromptFolder?: string,
|
||||
checkV1DefaultFolder: boolean = false,
|
||||
): Promise<{ path: string; content: string }[]> {
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
let promptFiles: { path: string; content: string }[] = [];
|
||||
const pathModule = await getPathModuleForIde(ide);
|
||||
|
||||
let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2];
|
||||
if (checkV1DefaultFolder) {
|
||||
dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1);
|
||||
}
|
||||
if (overridePromptFolder) {
|
||||
dirsToCheck = [overridePromptFolder];
|
||||
}
|
||||
|
||||
const fullDirs = workspaceDirs
|
||||
.map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d)))
|
||||
.flat();
|
||||
|
||||
promptFiles = (
|
||||
await Promise.all(
|
||||
workspaceDirs.map((dir) =>
|
||||
getPromptFilesFromDir(
|
||||
ide,
|
||||
pathModule.join(
|
||||
dir,
|
||||
overridePromptFolder ?? pathModule.join(".continue", "prompts"),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
)
|
||||
.flat()
|
||||
.filter(({ path }) => path.endsWith(".prompt"));
|
||||
await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir)))
|
||||
).flat();
|
||||
|
||||
// Also read from ~/.continue/.prompts
|
||||
promptFiles.push(...readAllGlobalPromptFiles());
|
||||
|
|
|
|||
|
|
@ -1,9 +1,8 @@
|
|||
import * as YAML from "yaml";
|
||||
|
||||
import { getBasename } from "../../util";
|
||||
import { getLastNPathParts } from "../../util/uri";
|
||||
|
||||
export function extractName(preamble: { name?: string }, path: string): string {
|
||||
return preamble.name ?? getBasename(path).split(".prompt")[0];
|
||||
return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
|
||||
}
|
||||
|
||||
export function getPreambleAndBody(content: string): [string, string] {
|
||||
|
|
|
|||
23
core/promptFiles/v2/parsePromptFileV1V2.ts
Normal file
23
core/promptFiles/v2/parsePromptFileV1V2.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import * as YAML from "yaml";
|
||||
import { getLastNPathParts } from "../../util/uri";
|
||||
|
||||
export function parsePromptFileV1V2(path: string, content: string) {
|
||||
let [preambleRaw, prompt] = content.split("\n---\n");
|
||||
if (prompt === undefined) {
|
||||
prompt = preambleRaw;
|
||||
preambleRaw = "";
|
||||
}
|
||||
|
||||
const preamble = YAML.parse(preambleRaw) ?? {};
|
||||
const name = preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
|
||||
const description = preamble.description ?? name;
|
||||
const version = preamble.version ?? 2;
|
||||
|
||||
let systemMessage: string | undefined = undefined;
|
||||
if (prompt.includes("<system>")) {
|
||||
systemMessage = prompt.split("<system>")[1].split("</system>")[0].trim();
|
||||
prompt = prompt.split("</system>")[1].trim();
|
||||
}
|
||||
|
||||
return { name, description, systemMessage, prompt, version };
|
||||
}
|
||||
|
|
@ -1,7 +1,8 @@
|
|||
import { ContextItem, ContextProviderExtras } from "../..";
|
||||
import { contextProviderClassFromName } from "../../context/providers";
|
||||
import URLContextProvider from "../../context/providers/URLContextProvider";
|
||||
import { getBasename } from "../../util";
|
||||
import { resolveRelativePathInDir } from "../../util/ideUtils";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
import { getPreambleAndBody } from "./parse";
|
||||
|
||||
async function resolveAttachment(
|
||||
|
|
@ -25,7 +26,8 @@ async function resolveAttachment(
|
|||
}
|
||||
|
||||
// Files
|
||||
if (await extras.ide.fileExists(name)) {
|
||||
const resolvedFileUri = await resolveRelativePathInDir(name, extras.ide);
|
||||
if (resolvedFileUri) {
|
||||
let subItems: ContextItem[] = [];
|
||||
if (name.endsWith(".prompt")) {
|
||||
// Recurse
|
||||
|
|
@ -36,10 +38,14 @@ async function resolveAttachment(
|
|||
subItems.push(...items);
|
||||
}
|
||||
|
||||
const content = `\`\`\`${name}\n${await extras.ide.readFile(name)}\n\`\`\``;
|
||||
const content = `\`\`\`${name}\n${await extras.ide.readFile(resolvedFileUri)}\n\`\`\``;
|
||||
return [
|
||||
...subItems,
|
||||
{ name: getBasename(name), content, description: name },
|
||||
{
|
||||
name: getUriPathBasename(resolvedFileUri),
|
||||
content,
|
||||
description: resolvedFileUri,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -159,7 +159,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
undefined | { dirs?: string[]; shouldClearIndexes?: boolean },
|
||||
void,
|
||||
];
|
||||
"index/forceReIndexFiles": [undefined | { files?: string[] }, void];
|
||||
"index/indexingProgressBarInitialized": [undefined, void];
|
||||
completeOnboarding: [
|
||||
{
|
||||
|
|
@ -168,6 +167,12 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
void,
|
||||
];
|
||||
|
||||
// File changes
|
||||
"files/changed": [{ uris?: string[] }, void];
|
||||
"files/opened": [{ uris?: string[] }, void];
|
||||
"files/created": [{ uris?: string[] }, void];
|
||||
"files/deleted": [{ uris?: string[] }, void];
|
||||
|
||||
// Docs etc. Indexing. TODO move codebase to this
|
||||
"indexing/reindex": [{ type: string; id: string }, void];
|
||||
"indexing/abort": [{ type: string; id: string }, void];
|
||||
|
|
|
|||
|
|
@ -23,10 +23,8 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
// Methods from IDE type
|
||||
getIdeInfo: [undefined, IdeInfo];
|
||||
getWorkspaceDirs: [undefined, string[]];
|
||||
listFolders: [undefined, string[]];
|
||||
writeFile: [{ path: string; contents: string }, void];
|
||||
showVirtualFile: [{ name: string; content: string }, void];
|
||||
getContinueDir: [undefined, string];
|
||||
openFile: [{ path: string }, void];
|
||||
openUrl: [string, void];
|
||||
runCommand: [{ command: string }, void];
|
||||
|
|
@ -35,10 +33,6 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
saveFile: [{ filepath: string }, void];
|
||||
fileExists: [{ filepath: string }, boolean];
|
||||
readFile: [{ filepath: string }, string];
|
||||
showDiff: [
|
||||
{ filepath: string; newContents: string; stepIndex: number },
|
||||
void,
|
||||
];
|
||||
diffLine: [
|
||||
{
|
||||
diffLine: DiffLine;
|
||||
|
|
@ -100,7 +94,6 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
ControlPlaneSessionInfo | undefined,
|
||||
];
|
||||
logoutOfControlPlane: [undefined, void];
|
||||
pathSep: [undefined, string];
|
||||
};
|
||||
|
||||
export type ToWebviewOrCoreFromIdeProtocol = {
|
||||
|
|
|
|||
|
|
@ -27,16 +27,13 @@ export class MessageIde implements IDE {
|
|||
) => void,
|
||||
) {}
|
||||
|
||||
pathSep(): Promise<string> {
|
||||
return this.request("pathSep", undefined);
|
||||
}
|
||||
fileExists(filepath: string): Promise<boolean> {
|
||||
return this.request("fileExists", { filepath });
|
||||
fileExists(fileUri: string): Promise<boolean> {
|
||||
return this.request("fileExists", { filepath: fileUri });
|
||||
}
|
||||
async gotoDefinition(location: Location): Promise<RangeInFile[]> {
|
||||
return this.request("gotoDefinition", { location });
|
||||
}
|
||||
onDidChangeActiveTextEditor(callback: (filepath: string) => void): void {
|
||||
onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void {
|
||||
this.on("didChangeActiveTextEditor", (data) => callback(data.filepath));
|
||||
}
|
||||
|
||||
|
|
@ -126,38 +123,27 @@ export class MessageIde implements IDE {
|
|||
}
|
||||
|
||||
async showLines(
|
||||
filepath: string,
|
||||
fileUri: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
): Promise<void> {
|
||||
return await this.request("showLines", { filepath, startLine, endLine });
|
||||
return await this.request("showLines", {
|
||||
filepath: fileUri,
|
||||
startLine,
|
||||
endLine,
|
||||
});
|
||||
}
|
||||
|
||||
async listFolders(): Promise<string[]> {
|
||||
return await this.request("listFolders", undefined);
|
||||
}
|
||||
|
||||
_continueDir: string | null = null;
|
||||
|
||||
async getContinueDir(): Promise<string> {
|
||||
if (this._continueDir) {
|
||||
return this._continueDir;
|
||||
}
|
||||
const dir = await this.request("getContinueDir", undefined);
|
||||
this._continueDir = dir;
|
||||
return dir;
|
||||
}
|
||||
|
||||
async writeFile(path: string, contents: string): Promise<void> {
|
||||
await this.request("writeFile", { path, contents });
|
||||
async writeFile(fileUri: string, contents: string): Promise<void> {
|
||||
await this.request("writeFile", { path: fileUri, contents });
|
||||
}
|
||||
|
||||
async showVirtualFile(title: string, contents: string): Promise<void> {
|
||||
await this.request("showVirtualFile", { name: title, content: contents });
|
||||
}
|
||||
|
||||
async openFile(path: string): Promise<void> {
|
||||
await this.request("openFile", { path });
|
||||
async openFile(fileUri: string): Promise<void> {
|
||||
await this.request("openFile", { path: fileUri });
|
||||
}
|
||||
|
||||
async openUrl(url: string): Promise<void> {
|
||||
|
|
@ -168,18 +154,11 @@ export class MessageIde implements IDE {
|
|||
await this.request("runCommand", { command });
|
||||
}
|
||||
|
||||
async saveFile(filepath: string): Promise<void> {
|
||||
await this.request("saveFile", { filepath });
|
||||
async saveFile(fileUri: string): Promise<void> {
|
||||
await this.request("saveFile", { filepath: fileUri });
|
||||
}
|
||||
async readFile(filepath: string): Promise<string> {
|
||||
return await this.request("readFile", { filepath });
|
||||
}
|
||||
async showDiff(
|
||||
filepath: string,
|
||||
newContents: string,
|
||||
stepIndex: number,
|
||||
): Promise<void> {
|
||||
await this.request("showDiff", { filepath, newContents, stepIndex });
|
||||
async readFile(fileUri: string): Promise<string> {
|
||||
return await this.request("readFile", { filepath: fileUri });
|
||||
}
|
||||
|
||||
getOpenFiles(): Promise<string[]> {
|
||||
|
|
@ -198,8 +177,8 @@ export class MessageIde implements IDE {
|
|||
return this.request("getSearchResults", { query });
|
||||
}
|
||||
|
||||
getProblems(filepath: string): Promise<Problem[]> {
|
||||
return this.request("getProblems", { filepath });
|
||||
getProblems(fileUri: string): Promise<Problem[]> {
|
||||
return this.request("getProblems", { filepath: fileUri });
|
||||
}
|
||||
|
||||
subprocess(command: string, cwd?: string): Promise<[string, string]> {
|
||||
|
|
|
|||
|
|
@ -117,19 +117,11 @@ export class ReverseMessageIde {
|
|||
return this.ide.showLines(data.filepath, data.startLine, data.endLine);
|
||||
});
|
||||
|
||||
this.on("listFolders", () => {
|
||||
return this.ide.listFolders();
|
||||
});
|
||||
|
||||
this.on("getControlPlaneSessionInfo", async (msg) => {
|
||||
// Not supported in testing
|
||||
return undefined;
|
||||
});
|
||||
|
||||
this.on("getContinueDir", () => {
|
||||
return this.ide.getContinueDir();
|
||||
});
|
||||
|
||||
this.on("writeFile", (data) => {
|
||||
return this.ide.writeFile(data.path, data.contents);
|
||||
});
|
||||
|
|
@ -158,10 +150,6 @@ export class ReverseMessageIde {
|
|||
return this.ide.readFile(data.filepath);
|
||||
});
|
||||
|
||||
this.on("showDiff", (data) => {
|
||||
return this.ide.showDiff(data.filepath, data.newContents, data.stepIndex);
|
||||
});
|
||||
|
||||
this.on("getOpenFiles", () => {
|
||||
return this.ide.getOpenFiles();
|
||||
});
|
||||
|
|
@ -189,8 +177,5 @@ export class ReverseMessageIde {
|
|||
this.on("getBranch", (data) => {
|
||||
return this.ide.getBranch(data.dir);
|
||||
});
|
||||
this.on("pathSep", (data) => {
|
||||
return this.ide.pathSep();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,7 +44,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
// Codebase
|
||||
"index/setPaused",
|
||||
"index/forceReIndex",
|
||||
"index/forceReIndexFiles",
|
||||
"index/indexingProgressBarInitialized",
|
||||
// Docs, etc.
|
||||
"indexing/reindex",
|
||||
|
|
|
|||
|
|
@ -1,20 +1,22 @@
|
|||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import { localPathToUri, localPathOrUriToPath } from "../util/pathToUri";
|
||||
|
||||
// Want this outside of the git repository so we can change branches in tests
|
||||
export const TEST_DIR = path.join(os.tmpdir(), "testWorkspaceDir");
|
||||
export const TEST_DIR_PATH = path.join(os.tmpdir(), "testWorkspaceDir");
|
||||
export const TEST_DIR = localPathToUri(TEST_DIR_PATH); // URI
|
||||
|
||||
export function setUpTestDir() {
|
||||
if (fs.existsSync(TEST_DIR)) {
|
||||
fs.rmSync(TEST_DIR, { recursive: true });
|
||||
if (fs.existsSync(TEST_DIR_PATH)) {
|
||||
fs.rmSync(TEST_DIR_PATH, { recursive: true });
|
||||
}
|
||||
fs.mkdirSync(TEST_DIR);
|
||||
fs.mkdirSync(TEST_DIR_PATH);
|
||||
}
|
||||
|
||||
export function tearDownTestDir() {
|
||||
if (fs.existsSync(TEST_DIR)) {
|
||||
fs.rmSync(TEST_DIR, { recursive: true });
|
||||
if (fs.existsSync(TEST_DIR_PATH)) {
|
||||
fs.rmSync(TEST_DIR_PATH, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -24,15 +26,24 @@ export function tearDownTestDir() {
|
|||
"index/index.ts" creates an empty index/index.ts
|
||||
["index/index.ts", "hello"] creates index/index.ts with contents "hello"
|
||||
*/
|
||||
export function addToTestDir(paths: (string | string[])[]) {
|
||||
export function addToTestDir(pathsOrUris: (string | string[])[]) {
|
||||
// Allow tests to use URIs or local paths
|
||||
const paths = pathsOrUris.map((val) => {
|
||||
if (Array.isArray(val)) {
|
||||
return [localPathOrUriToPath(val[0]), val[1]];
|
||||
} else {
|
||||
return localPathOrUriToPath(val);
|
||||
}
|
||||
});
|
||||
|
||||
for (const p of paths) {
|
||||
const filepath = path.join(TEST_DIR, Array.isArray(p) ? p[0] : p);
|
||||
const filepath = path.join(TEST_DIR_PATH, Array.isArray(p) ? p[0] : p);
|
||||
fs.mkdirSync(path.dirname(filepath), { recursive: true });
|
||||
|
||||
if (Array.isArray(p)) {
|
||||
fs.writeFileSync(filepath, p[1]);
|
||||
} else if (p.endsWith("/")) {
|
||||
fs.mkdirSync(filepath, { recursive: true });
|
||||
fs.mkdirSync(p, { recursive: true });
|
||||
} else {
|
||||
fs.writeFileSync(filepath, "");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,17 +1,15 @@
|
|||
import { getPathModuleForIde } from "../../util/pathModule";
|
||||
import { inferResolvedUriFromRelativePath } from "../../util/ideUtils";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
|
||||
export const createNewFileImpl: ToolImpl = async (args, extras) => {
|
||||
const pathSep = await extras.ide.pathSep();
|
||||
let filepath = args.filepath;
|
||||
if (!args.filepath.startsWith(pathSep)) {
|
||||
const pathModule = await getPathModuleForIde(extras.ide);
|
||||
const workspaceDirs = await extras.ide.getWorkspaceDirs();
|
||||
const cwd = workspaceDirs[0];
|
||||
filepath = pathModule.join(cwd, filepath);
|
||||
const resolvedFilepath = await inferResolvedUriFromRelativePath(
|
||||
args.filepath,
|
||||
extras.ide,
|
||||
);
|
||||
if (resolvedFilepath) {
|
||||
await extras.ide.writeFile(resolvedFilepath, args.contents);
|
||||
await extras.ide.openFile(resolvedFilepath);
|
||||
}
|
||||
await extras.ide.writeFile(filepath, args.contents);
|
||||
await extras.ide.openFile(filepath);
|
||||
return [];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { getBasename } from "../../util";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
|
||||
export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => {
|
||||
const result = await extras.ide.getCurrentFile();
|
||||
|
|
@ -8,7 +8,7 @@ export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => {
|
|||
return [];
|
||||
}
|
||||
|
||||
const basename = getBasename(result.path);
|
||||
const basename = getUriPathBasename(result.path);
|
||||
|
||||
return [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,12 +1,11 @@
|
|||
import { getBasename } from "../../util";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
|
||||
export const readFileImpl: ToolImpl = async (args, extras) => {
|
||||
const content = await extras.ide.readFile(args.filepath);
|
||||
return [
|
||||
{
|
||||
name: getBasename(args.filepath),
|
||||
name: getUriPathBasename(args.filepath),
|
||||
description: args.filepath,
|
||||
content,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import childProcess from "node:child_process";
|
|||
import util from "node:util";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const asyncExec = util.promisify(childProcess.exec);
|
||||
|
||||
|
|
@ -11,7 +12,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
if (ideInfo.remoteName === "local" || ideInfo.remoteName === "") {
|
||||
try {
|
||||
const output = await asyncExec(args.command, {
|
||||
cwd: (await extras.ide.getWorkspaceDirs())[0],
|
||||
cwd: fileURLToPath((await extras.ide.getWorkspaceDirs())[0]),
|
||||
});
|
||||
return [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -3,7 +3,10 @@ import generateRepoMap from "../../util/generateRepoMap";
|
|||
import { ToolImpl } from ".";
|
||||
|
||||
export const viewRepoMapImpl: ToolImpl = async (args, extras) => {
|
||||
const repoMap = await generateRepoMap(extras.llm, extras.ide, {});
|
||||
const repoMap = await generateRepoMap(extras.llm, extras.ide, {
|
||||
outputRelativeUriPaths: true,
|
||||
includeSignatures: false,
|
||||
});
|
||||
return [
|
||||
{
|
||||
name: "Repo map",
|
||||
|
|
|
|||
|
|
@ -1,22 +1,22 @@
|
|||
import generateRepoMap from "../../util/generateRepoMap";
|
||||
import { resolveRelativePathInWorkspace } from "../../util/ideUtils";
|
||||
import { resolveRelativePathInDir } from "../../util/ideUtils";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
|
||||
export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => {
|
||||
const { directory_path } = args;
|
||||
const absolutePath = await resolveRelativePathInWorkspace(
|
||||
directory_path,
|
||||
extras.ide,
|
||||
);
|
||||
const uri = await resolveRelativePathInDir(directory_path, extras.ide);
|
||||
|
||||
if (!absolutePath) {
|
||||
if (!uri) {
|
||||
throw new Error(`Directory path "${directory_path}" does not exist.`);
|
||||
}
|
||||
|
||||
const repoMap = await generateRepoMap(extras.llm, extras.ide, {
|
||||
dirs: [absolutePath],
|
||||
dirUris: [uri],
|
||||
outputRelativeUriPaths: true,
|
||||
includeSignatures: false,
|
||||
});
|
||||
|
||||
return [
|
||||
{
|
||||
name: "Repo map",
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ export type GlobalContextType = {
|
|||
curEmbeddingsProviderId: string;
|
||||
hasDismissedConfigTsNoticeJetBrains: boolean;
|
||||
hasAlreadyCreatedAPromptFile: boolean;
|
||||
showConfigUpdateToast: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { writeFileSync } from "fs";
|
||||
import fs from "fs";
|
||||
|
||||
import { getDevDataFilePath } from "./paths.js";
|
||||
|
||||
export function logDevData(tableName: string, data: any) {
|
||||
const filepath: string = getDevDataFilePath(tableName);
|
||||
const jsonLine = JSON.stringify(data);
|
||||
writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
|
||||
fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
|
||||
import {
|
||||
ContinueRcJson,
|
||||
|
|
@ -14,10 +13,9 @@ import {
|
|||
RangeInFile,
|
||||
Thread,
|
||||
ToastType,
|
||||
} from "../index.d.js";
|
||||
} from "../index.js";
|
||||
import { GetGhTokenArgs } from "../protocol/ide.js";
|
||||
|
||||
import { getContinueGlobalPath } from "./paths.js";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
class FileSystemIde implements IDE {
|
||||
constructor(private readonly workspaceDir: string) {}
|
||||
|
|
@ -28,17 +26,15 @@ class FileSystemIde implements IDE {
|
|||
): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
pathSep(): Promise<string> {
|
||||
return Promise.resolve(path.sep);
|
||||
}
|
||||
fileExists(filepath: string): Promise<boolean> {
|
||||
fileExists(fileUri: string): Promise<boolean> {
|
||||
const filepath = fileURLToPath(fileUri);
|
||||
return Promise.resolve(fs.existsSync(filepath));
|
||||
}
|
||||
|
||||
gotoDefinition(location: Location): Promise<RangeInFile[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
onDidChangeActiveTextEditor(callback: (filepath: string) => void): void {
|
||||
onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -55,14 +51,17 @@ class FileSystemIde implements IDE {
|
|||
async getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined> {
|
||||
return undefined;
|
||||
}
|
||||
async getLastModified(files: string[]): Promise<{ [path: string]: number }> {
|
||||
async getLastModified(
|
||||
fileUris: string[],
|
||||
): Promise<{ [path: string]: number }> {
|
||||
const result: { [path: string]: number } = {};
|
||||
for (const file of files) {
|
||||
for (const uri of fileUris) {
|
||||
try {
|
||||
const stats = fs.statSync(file);
|
||||
result[file] = stats.mtimeMs;
|
||||
const filepath = fileURLToPath(uri);
|
||||
const stats = fs.statSync(filepath);
|
||||
result[uri] = stats.mtimeMs;
|
||||
} catch (error) {
|
||||
console.error(`Error getting last modified time for ${file}:`, error);
|
||||
console.error(`Error getting last modified time for ${uri}:`, error);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
|
|
@ -71,8 +70,9 @@ class FileSystemIde implements IDE {
|
|||
return Promise.resolve(dir);
|
||||
}
|
||||
async listDir(dir: string): Promise<[string, FileType][]> {
|
||||
const filepath = fileURLToPath(dir);
|
||||
const all: [string, FileType][] = fs
|
||||
.readdirSync(dir, { withFileTypes: true })
|
||||
.readdirSync(filepath, { withFileTypes: true })
|
||||
.map((dirent: any) => [
|
||||
dirent.name,
|
||||
dirent.isDirectory()
|
||||
|
|
@ -109,7 +109,7 @@ class FileSystemIde implements IDE {
|
|||
});
|
||||
}
|
||||
|
||||
readRangeInFile(filepath: string, range: Range): Promise<string> {
|
||||
readRangeInFile(fileUri: string, range: Range): Promise<string> {
|
||||
return Promise.resolve("");
|
||||
}
|
||||
|
||||
|
|
@ -153,7 +153,7 @@ class FileSystemIde implements IDE {
|
|||
}
|
||||
|
||||
showLines(
|
||||
filepath: string,
|
||||
fileUri: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
): Promise<void> {
|
||||
|
|
@ -164,13 +164,10 @@ class FileSystemIde implements IDE {
|
|||
return Promise.resolve([this.workspaceDir]);
|
||||
}
|
||||
|
||||
listFolders(): Promise<string[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
writeFile(path: string, contents: string): Promise<void> {
|
||||
writeFile(fileUri: string, contents: string): Promise<void> {
|
||||
const filepath = fileURLToPath(fileUri);
|
||||
return new Promise((resolve, reject) => {
|
||||
fs.writeFile(path, contents, (err) => {
|
||||
fs.writeFile(filepath, contents, (err) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
|
|
@ -183,10 +180,6 @@ class FileSystemIde implements IDE {
|
|||
return Promise.resolve();
|
||||
}
|
||||
|
||||
getContinueDir(): Promise<string> {
|
||||
return Promise.resolve(getContinueGlobalPath());
|
||||
}
|
||||
|
||||
openFile(path: string): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
|
@ -199,11 +192,12 @@ class FileSystemIde implements IDE {
|
|||
return Promise.resolve();
|
||||
}
|
||||
|
||||
saveFile(filepath: string): Promise<void> {
|
||||
saveFile(fileUri: string): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
readFile(filepath: string): Promise<string> {
|
||||
readFile(fileUri: string): Promise<string> {
|
||||
const filepath = fileURLToPath(fileUri);
|
||||
return new Promise((resolve, reject) => {
|
||||
fs.readFile(filepath, "utf8", (err, contents) => {
|
||||
if (err) {
|
||||
|
|
@ -218,14 +212,6 @@ class FileSystemIde implements IDE {
|
|||
return Promise.resolve(undefined);
|
||||
}
|
||||
|
||||
showDiff(
|
||||
filepath: string,
|
||||
newContents: string,
|
||||
stepIndex: number,
|
||||
): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
getBranch(dir: string): Promise<string> {
|
||||
return Promise.resolve("");
|
||||
}
|
||||
|
|
@ -242,7 +228,7 @@ class FileSystemIde implements IDE {
|
|||
return "";
|
||||
}
|
||||
|
||||
async getProblems(filepath?: string | undefined): Promise<Problem[]> {
|
||||
async getProblems(fileUri?: string | undefined): Promise<Problem[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ describe.skip("generateRepoMap", () => {
|
|||
.mockImplementation(async (dirs, offset, limit) => {
|
||||
// Return test data
|
||||
return {
|
||||
groupedByPath: {
|
||||
groupedByUri: {
|
||||
[path.join(TEST_DIR, "file1.js")]: [
|
||||
"function foo() {}",
|
||||
"function bar() {}",
|
||||
|
|
@ -60,6 +60,7 @@ describe.skip("generateRepoMap", () => {
|
|||
// Act
|
||||
const repoMapContent = await generateRepoMap(testLLM, testIde, {
|
||||
includeSignatures: true,
|
||||
outputRelativeUriPaths: true,
|
||||
});
|
||||
|
||||
// Assert
|
||||
|
|
@ -103,7 +104,7 @@ describe.skip("generateRepoMap", () => {
|
|||
.mockImplementation(async (dirs, offset, limit) => {
|
||||
// Return test data
|
||||
return {
|
||||
groupedByPath: {
|
||||
groupedByUri: {
|
||||
[path.join(TEST_DIR, "file1.js")]: [],
|
||||
[path.join(TEST_DIR, "subdir/file2.py")]: [],
|
||||
},
|
||||
|
|
@ -118,6 +119,7 @@ describe.skip("generateRepoMap", () => {
|
|||
// Act
|
||||
const repoMapContent = await generateRepoMap(testLLM, testIde, {
|
||||
includeSignatures: false,
|
||||
outputRelativeUriPaths: true,
|
||||
});
|
||||
|
||||
// Assert
|
||||
|
|
@ -155,7 +157,7 @@ describe.skip("generateRepoMap", () => {
|
|||
.mockImplementation(async (dirs, offset, limit) => {
|
||||
// Return test data
|
||||
return {
|
||||
groupedByPath: {
|
||||
groupedByUri: {
|
||||
[path.join(TEST_DIR, "file1.js")]: ["function foo() {}"],
|
||||
[path.join(TEST_DIR, "subdir/file2.py")]: ["def foo():"],
|
||||
},
|
||||
|
|
@ -185,6 +187,7 @@ describe.skip("generateRepoMap", () => {
|
|||
// Act
|
||||
const repoMapContent = await generateRepoMap(testLLM, testIde, {
|
||||
includeSignatures: true,
|
||||
outputRelativeUriPaths: true,
|
||||
});
|
||||
|
||||
// Assert
|
||||
|
|
|
|||
|
|
@ -1,16 +1,17 @@
|
|||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { IDE, ILLM } from "..";
|
||||
import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex";
|
||||
import { walkDirAsync } from "../indexing/walkDir";
|
||||
import { walkDirs } from "../indexing/walkDir";
|
||||
import { pruneLinesFromTop } from "../llm/countTokens";
|
||||
|
||||
import { getRepoMapFilePath } from "./paths";
|
||||
import { findUriInDirs } from "./uri";
|
||||
|
||||
export interface RepoMapOptions {
|
||||
includeSignatures?: boolean;
|
||||
dirs?: string[];
|
||||
dirUris?: string[];
|
||||
outputRelativeUriPaths: boolean;
|
||||
}
|
||||
|
||||
class RepoMapGenerator {
|
||||
|
|
@ -19,8 +20,8 @@ class RepoMapGenerator {
|
|||
private repoMapPath: string = getRepoMapFilePath();
|
||||
private writeStream: fs.WriteStream = fs.createWriteStream(this.repoMapPath);
|
||||
private contentTokens: number = 0;
|
||||
private repoMapDirs: string[] = [];
|
||||
private allPathsInDirs: Set<string> = new Set();
|
||||
private dirs: string[] = [];
|
||||
private allUris: string[] = [];
|
||||
private pathsInDirsWithSnippets: Set<string> = new Set();
|
||||
|
||||
private BATCH_SIZE = 100;
|
||||
|
|
@ -40,118 +41,100 @@ class RepoMapGenerator {
|
|||
llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO;
|
||||
}
|
||||
|
||||
private getUriForWrite(uri: string) {
|
||||
if (this.options.outputRelativeUriPaths) {
|
||||
return findUriInDirs(uri, this.dirs).relativePathOrBasename;
|
||||
}
|
||||
return uri;
|
||||
}
|
||||
|
||||
async generate(): Promise<string> {
|
||||
this.repoMapDirs = this.options.dirs ?? (await this.ide.getWorkspaceDirs());
|
||||
this.allPathsInDirs = await this.getAllPathsInDirs();
|
||||
this.dirs = this.options.dirUris ?? (await this.ide.getWorkspaceDirs());
|
||||
this.allUris = await walkDirs(this.ide, undefined, this.dirs);
|
||||
|
||||
await this.initializeWriteStream();
|
||||
await this.processPathsAndSignatures();
|
||||
|
||||
this.writeStream.end();
|
||||
this.logRepoMapGeneration();
|
||||
|
||||
return fs.readFileSync(this.repoMapPath, "utf8");
|
||||
}
|
||||
|
||||
private async initializeWriteStream(): Promise<void> {
|
||||
// Initialize
|
||||
await this.writeToStream(this.PREAMBLE);
|
||||
this.contentTokens += this.llm.countTokens(this.PREAMBLE);
|
||||
}
|
||||
|
||||
private async getAllPathsInDirs(): Promise<Set<string>> {
|
||||
const paths = new Set<string>();
|
||||
if (this.options.includeSignatures) {
|
||||
// Process uris and signatures
|
||||
let offset = 0;
|
||||
while (true) {
|
||||
const { groupedByUri, hasMore } =
|
||||
await CodeSnippetsCodebaseIndex.getPathsAndSignatures(
|
||||
this.allUris,
|
||||
offset,
|
||||
this.BATCH_SIZE,
|
||||
);
|
||||
// process batch
|
||||
for (const [uri, signatures] of Object.entries(groupedByUri)) {
|
||||
let fileContent: string;
|
||||
|
||||
for (const dir of this.repoMapDirs) {
|
||||
for await (const filepath of walkDirAsync(dir, this.ide)) {
|
||||
paths.add(filepath.replace(dir, "").slice(1));
|
||||
try {
|
||||
fileContent = await this.ide.readFile(uri);
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"Failed to read file:\n" +
|
||||
` Uri: ${uri}\n` +
|
||||
` Error: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
const filteredSignatures = signatures.filter(
|
||||
(signature) => signature.trim() !== fileContent.trim(),
|
||||
);
|
||||
|
||||
if (filteredSignatures.length > 0) {
|
||||
this.pathsInDirsWithSnippets.add(uri);
|
||||
}
|
||||
|
||||
let content = `${this.getUriForWrite(uri)}:\n`;
|
||||
|
||||
for (const signature of signatures.slice(0, -1)) {
|
||||
content += `${this.indentMultilineString(signature)}\n\t...\n`;
|
||||
}
|
||||
|
||||
content += `${this.indentMultilineString(
|
||||
signatures[signatures.length - 1],
|
||||
)}\n\n`;
|
||||
|
||||
if (content) {
|
||||
await this.writeToStream(content);
|
||||
}
|
||||
}
|
||||
if (!hasMore || this.contentTokens >= this.maxRepoMapTokens) {
|
||||
break;
|
||||
}
|
||||
offset += this.BATCH_SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
return paths;
|
||||
}
|
||||
|
||||
private async processPathsAndSignatures(): Promise<void> {
|
||||
let offset = 0;
|
||||
while (true) {
|
||||
const { groupedByPath, hasMore } =
|
||||
await CodeSnippetsCodebaseIndex.getPathsAndSignatures(
|
||||
this.repoMapDirs,
|
||||
offset,
|
||||
this.BATCH_SIZE,
|
||||
);
|
||||
await this.processBatch(groupedByPath);
|
||||
if (!hasMore || this.contentTokens >= this.maxRepoMapTokens) {
|
||||
break;
|
||||
}
|
||||
offset += this.BATCH_SIZE;
|
||||
}
|
||||
await this.writeRemainingPaths();
|
||||
}
|
||||
|
||||
private async processBatch(
|
||||
groupedByPath: Record<string, string[]>,
|
||||
): Promise<void> {
|
||||
for (const [absolutePath, signatures] of Object.entries(groupedByPath)) {
|
||||
const content = await this.processFile(absolutePath, signatures);
|
||||
|
||||
if (content) {
|
||||
await this.writeToStream(content);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async processFile(
|
||||
absolutePath: string,
|
||||
signatures: string[],
|
||||
): Promise<string | undefined> {
|
||||
const workspaceDir =
|
||||
this.repoMapDirs.find((dir) => absolutePath.startsWith(dir)) || "";
|
||||
const relativePath = path.relative(workspaceDir, absolutePath);
|
||||
|
||||
let fileContent: string;
|
||||
|
||||
try {
|
||||
fileContent = await fs.promises.readFile(absolutePath, "utf8");
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"Failed to read file:\n" +
|
||||
` Path: ${absolutePath}\n` +
|
||||
` Error: ${err instanceof Error ? err.message : String(err)}`,
|
||||
// Remaining Uris just so that written repo map isn't incomplete
|
||||
const urisWithoutSnippets = this.allUris.filter(
|
||||
(uri) => !this.pathsInDirsWithSnippets.has(uri),
|
||||
);
|
||||
|
||||
return;
|
||||
if (urisWithoutSnippets.length > 0) {
|
||||
await this.writeToStream(
|
||||
urisWithoutSnippets.map((uri) => this.getUriForWrite(uri)).join("\n"),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// Only process uris
|
||||
await this.writeToStream(
|
||||
this.allUris.map((uri) => this.getUriForWrite(uri)).join("\n"),
|
||||
);
|
||||
}
|
||||
|
||||
const filteredSignatures = signatures.filter(
|
||||
(signature) => signature.trim() !== fileContent.trim(),
|
||||
);
|
||||
this.writeStream.end();
|
||||
|
||||
if (filteredSignatures.length > 0) {
|
||||
this.pathsInDirsWithSnippets.add(relativePath);
|
||||
if (this.contentTokens >= this.maxRepoMapTokens) {
|
||||
console.debug(
|
||||
"Full repo map was unable to be generated due to context window limitations",
|
||||
);
|
||||
}
|
||||
|
||||
return this.generateContentForPath(relativePath, filteredSignatures);
|
||||
}
|
||||
|
||||
private generateContentForPath(
|
||||
relativePath: string,
|
||||
signatures: string[],
|
||||
): string {
|
||||
if (this.options.includeSignatures === false) {
|
||||
return `${relativePath}\n`;
|
||||
}
|
||||
|
||||
let content = `${relativePath}:\n`;
|
||||
|
||||
for (const signature of signatures.slice(0, -1)) {
|
||||
content += `${this.indentMultilineString(signature)}\n\t...\n`;
|
||||
}
|
||||
|
||||
content += `${this.indentMultilineString(
|
||||
signatures[signatures.length - 1],
|
||||
)}\n\n`;
|
||||
|
||||
return content;
|
||||
return fs.readFileSync(this.repoMapPath, "utf8");
|
||||
}
|
||||
|
||||
private async writeToStream(content: string): Promise<void> {
|
||||
|
|
@ -170,26 +153,6 @@ class RepoMapGenerator {
|
|||
await new Promise((resolve) => this.writeStream.write(content, resolve));
|
||||
}
|
||||
|
||||
private async writeRemainingPaths(): Promise<void> {
|
||||
const pathsWithoutSnippets = new Set(
|
||||
[...this.allPathsInDirs].filter(
|
||||
(x) => !this.pathsInDirsWithSnippets.has(x),
|
||||
),
|
||||
);
|
||||
|
||||
if (pathsWithoutSnippets.size > 0) {
|
||||
await this.writeToStream(Array.from(pathsWithoutSnippets).join("\n"));
|
||||
}
|
||||
}
|
||||
|
||||
private logRepoMapGeneration(): void {
|
||||
if (this.contentTokens >= this.maxRepoMapTokens) {
|
||||
console.debug(
|
||||
"Full repo map was unable to be generated due to context window limitations",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private indentMultilineString(str: string) {
|
||||
return str
|
||||
.split("\n")
|
||||
|
|
|
|||
|
|
@ -1,48 +0,0 @@
|
|||
// Generated by continue
|
||||
|
||||
import { resolveRelativePathInWorkspace } from "./ideUtils";
|
||||
import { testIde } from "../test/fixtures";
|
||||
import { IDE } from "..";
|
||||
|
||||
describe("resolveRelativePathInWorkspace", () => {
|
||||
let mockIde: IDE;
|
||||
|
||||
beforeEach(() => {
|
||||
mockIde = testIde;
|
||||
});
|
||||
|
||||
it("should return the full path if the path is already absolute", async () => {
|
||||
const mockPath = "/absolute/path/to/file.txt";
|
||||
jest.spyOn(mockIde, "pathSep").mockResolvedValue("/");
|
||||
|
||||
const result = await resolveRelativePathInWorkspace(mockPath, mockIde);
|
||||
expect(result).toBe(mockPath);
|
||||
});
|
||||
|
||||
it("should resolve a relative path to a full path within workspace directories", async () => {
|
||||
const relativePath = "relative/path/to/file.txt";
|
||||
const workspaces = ["/workspace/one", "/workspace/two"];
|
||||
const expectedFullPath = `/workspace/one/${relativePath}`;
|
||||
|
||||
jest.spyOn(mockIde, "pathSep").mockResolvedValue("/");
|
||||
jest.spyOn(mockIde, "getWorkspaceDirs").mockResolvedValue(workspaces);
|
||||
jest
|
||||
.spyOn(mockIde, "fileExists")
|
||||
.mockImplementation(async (path) => path === expectedFullPath);
|
||||
|
||||
const result = await resolveRelativePathInWorkspace(relativePath, mockIde);
|
||||
expect(result).toBe(expectedFullPath);
|
||||
});
|
||||
|
||||
it("should return undefined if the relative path does not exist in any workspace directory", async () => {
|
||||
const relativePath = "non/existent/path.txt";
|
||||
const workspaces = ["/workspace/one", "/workspace/two"];
|
||||
|
||||
jest.spyOn(mockIde, "pathSep").mockResolvedValue("/");
|
||||
jest.spyOn(mockIde, "getWorkspaceDirs").mockResolvedValue(workspaces);
|
||||
jest.spyOn(mockIde, "fileExists").mockResolvedValue(false);
|
||||
|
||||
const result = await resolveRelativePathInWorkspace(relativePath, mockIde);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -1,21 +1,80 @@
|
|||
import { IDE } from "..";
|
||||
import { joinPathsToUri, pathToUriPathSegment } from "./uri";
|
||||
|
||||
export async function resolveRelativePathInWorkspace(
|
||||
/*
|
||||
This function takes a relative (to workspace) filepath
|
||||
And checks each workspace for if it exists or not
|
||||
Only returns fully resolved URI if it exists
|
||||
*/
|
||||
export async function resolveRelativePathInDir(
|
||||
path: string,
|
||||
ide: IDE,
|
||||
dirUriCandidates?: string[],
|
||||
): Promise<string | undefined> {
|
||||
const pathSep = await ide.pathSep();
|
||||
if (path.startsWith(pathSep)) {
|
||||
return path;
|
||||
}
|
||||
|
||||
const workspaces = await ide.getWorkspaceDirs();
|
||||
for (const workspace of workspaces) {
|
||||
const fullPath = `${workspace}${pathSep}${path}`;
|
||||
if (await ide.fileExists(fullPath)) {
|
||||
return fullPath;
|
||||
const dirs = dirUriCandidates ?? (await ide.getWorkspaceDirs());
|
||||
for (const dirUri of dirs) {
|
||||
const fullUri = joinPathsToUri(dirUri, path);
|
||||
if (await ide.fileExists(fullUri)) {
|
||||
return fullUri;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/*
|
||||
Same as above but in this case the relative path does not need to exist (e.g. file to be created, etc)
|
||||
Checks closes match with the dirs, path segment by segment
|
||||
and based on which workspace has the closest matching path, returns resolved URI
|
||||
If no meaninful path match just concatenates to first dir's uri
|
||||
*/
|
||||
export async function inferResolvedUriFromRelativePath(
|
||||
path: string,
|
||||
ide: IDE,
|
||||
dirCandidates?: string[],
|
||||
): Promise<string> {
|
||||
const dirs = dirCandidates ?? (await ide.getWorkspaceDirs());
|
||||
console.log(path, dirs);
|
||||
if (dirs.length === 0) {
|
||||
throw new Error("inferResolvedUriFromRelativePath: no dirs provided");
|
||||
}
|
||||
const segments = pathToUriPathSegment(path).split("/");
|
||||
// Generate all possible suffixes from shortest to longest
|
||||
const suffixes: string[] = [];
|
||||
for (let i = segments.length - 1; i >= 0; i--) {
|
||||
suffixes.push(segments.slice(i).join("/"));
|
||||
}
|
||||
console.log(suffixes);
|
||||
|
||||
// For each suffix, try to find a unique matching directory
|
||||
for (const suffix of suffixes) {
|
||||
const uris = dirs.map((dir) => ({
|
||||
dir,
|
||||
partialUri: joinPathsToUri(dir, suffix),
|
||||
}));
|
||||
const promises = uris.map(async ({ partialUri, dir }) => {
|
||||
const exists = await ide.fileExists(partialUri);
|
||||
return {
|
||||
dir,
|
||||
partialUri,
|
||||
exists,
|
||||
};
|
||||
});
|
||||
const existenceChecks = await Promise.all(promises);
|
||||
|
||||
const existingUris = existenceChecks.filter(({ exists }) => exists);
|
||||
|
||||
// If exactly one directory matches, use it
|
||||
if (existingUris.length === 1) {
|
||||
return joinPathsToUri(existingUris[0].dir, segments.join("/"));
|
||||
}
|
||||
}
|
||||
|
||||
// If no unique match found, use the first directory
|
||||
return joinPathsToUri(dirs[0], path);
|
||||
}
|
||||
|
||||
interface ResolveResult {
|
||||
resolvedUri: string;
|
||||
matchedDir: string;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,58 +3,12 @@ import {
|
|||
dedent,
|
||||
dedentAndGetCommonWhitespace,
|
||||
deduplicateArray,
|
||||
getLastNPathParts,
|
||||
copyOf,
|
||||
getBasename,
|
||||
getMarkdownLanguageTagForFile,
|
||||
getRelativePath,
|
||||
getUniqueFilePath,
|
||||
groupByLastNPathParts,
|
||||
removeCodeBlocksAndTrim,
|
||||
removeQuotesAndEscapes,
|
||||
shortestRelativePaths,
|
||||
splitPath,
|
||||
} from "./";
|
||||
|
||||
describe("getLastNPathParts", () => {
|
||||
test("returns the last N parts of a filepath with forward slashes", () => {
|
||||
const filepath = "home/user/documents/project/file.txt";
|
||||
expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt");
|
||||
});
|
||||
|
||||
test("returns the last N parts of a filepath with backward slashes", () => {
|
||||
const filepath = "C:\\home\\user\\documents\\project\\file.txt";
|
||||
expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt");
|
||||
});
|
||||
|
||||
test("returns the last part if N is 1", () => {
|
||||
const filepath = "/home/user/documents/project/file.txt";
|
||||
expect(getLastNPathParts(filepath, 1)).toBe("file.txt");
|
||||
});
|
||||
|
||||
test("returns the entire path if N is greater than the number of parts", () => {
|
||||
const filepath = "home/user/documents/project/file.txt";
|
||||
expect(getLastNPathParts(filepath, 10)).toBe(
|
||||
"home/user/documents/project/file.txt",
|
||||
);
|
||||
});
|
||||
|
||||
test("returns an empty string if N is 0", () => {
|
||||
const filepath = "home/user/documents/project/file.txt";
|
||||
expect(getLastNPathParts(filepath, 0)).toBe("");
|
||||
});
|
||||
|
||||
test("handles paths with mixed forward and backward slashes", () => {
|
||||
const filepath = "home\\user/documents\\project/file.txt";
|
||||
expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt");
|
||||
});
|
||||
|
||||
test("handles edge case with empty filepath", () => {
|
||||
const filepath = "";
|
||||
expect(getLastNPathParts(filepath, 2)).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deduplicateArray", () => {
|
||||
it("should return an empty array when given an empty array", () => {
|
||||
const result = deduplicateArray([], (a, b) => a === b);
|
||||
|
|
@ -414,199 +368,6 @@ describe("removeQuotesAndEscapes", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("getBasename", () => {
|
||||
it("should return the base name of a Unix-style path", () => {
|
||||
const filepath = "/home/user/documents/file.txt";
|
||||
const output = getBasename(filepath);
|
||||
expect(output).toBe("file.txt");
|
||||
});
|
||||
|
||||
it("should return the base name of a Windows-style path", () => {
|
||||
const filepath = "C:\\Users\\User\\Documents\\file.txt";
|
||||
const output = getBasename(filepath);
|
||||
expect(output).toBe("file.txt");
|
||||
});
|
||||
|
||||
it("should handle paths with mixed separators", () => {
|
||||
const filepath = "C:/Users\\User/Documents/file.txt";
|
||||
const output = getBasename(filepath);
|
||||
expect(output).toBe("file.txt");
|
||||
});
|
||||
|
||||
it("should return an empty string for empty input", () => {
|
||||
const filepath = "";
|
||||
const output = getBasename(filepath);
|
||||
expect(output).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("groupByLastNPathParts", () => {
|
||||
it("should group filepaths by their last N parts", () => {
|
||||
const filepaths = [
|
||||
"/a/b/c/d/file1.txt",
|
||||
"/x/y/z/file1.txt",
|
||||
"/a/b/c/d/file2.txt",
|
||||
];
|
||||
const output = groupByLastNPathParts(filepaths, 2);
|
||||
expect(output).toEqual({
|
||||
"d/file1.txt": ["/a/b/c/d/file1.txt"],
|
||||
"z/file1.txt": ["/x/y/z/file1.txt"],
|
||||
"d/file2.txt": ["/a/b/c/d/file2.txt"],
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle an empty array", () => {
|
||||
const filepaths: string[] = [];
|
||||
const output = groupByLastNPathParts(filepaths, 2);
|
||||
expect(output).toEqual({});
|
||||
});
|
||||
|
||||
it("should handle N greater than path parts", () => {
|
||||
const filepaths = ["/file.txt"];
|
||||
const output = groupByLastNPathParts(filepaths, 5);
|
||||
expect(output).toEqual({ "/file.txt": ["/file.txt"] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("getUniqueFilePath", () => {
|
||||
it("should return a unique file path within the group", () => {
|
||||
const item = "/a/b/c/file.txt";
|
||||
const itemGroups = {
|
||||
"c/file.txt": ["/a/b/c/file.txt", "/x/y/c/file.txt"],
|
||||
};
|
||||
const output = getUniqueFilePath(item, itemGroups);
|
||||
expect(output).toBe("b/c/file.txt");
|
||||
});
|
||||
|
||||
it("should return the last two parts if unique", () => {
|
||||
const item = "/a/b/c/file.txt";
|
||||
const itemGroups = {
|
||||
"c/file.txt": ["/a/b/c/file.txt"],
|
||||
};
|
||||
const output = getUniqueFilePath(item, itemGroups);
|
||||
expect(output).toBe("c/file.txt");
|
||||
});
|
||||
|
||||
it("should handle when additional parts are needed to make it unique", () => {
|
||||
const item = "/a/b/c/d/e/file.txt";
|
||||
const itemGroups = {
|
||||
"e/file.txt": ["/a/b/c/d/e/file.txt", "/x/y/z/e/file.txt"],
|
||||
};
|
||||
const output = getUniqueFilePath(item, itemGroups);
|
||||
expect(output).toBe("d/e/file.txt");
|
||||
});
|
||||
});
|
||||
|
||||
describe("shortestRelativePaths", () => {
|
||||
it("should return shortest unique paths", () => {
|
||||
const paths = [
|
||||
"/a/b/c/file.txt",
|
||||
"/a/b/d/file.txt",
|
||||
"/a/b/d/file2.txt",
|
||||
"/x/y/z/file.txt",
|
||||
];
|
||||
const output = shortestRelativePaths(paths);
|
||||
expect(output).toEqual([
|
||||
"c/file.txt",
|
||||
"d/file.txt",
|
||||
"file2.txt",
|
||||
"z/file.txt",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle empty array", () => {
|
||||
const paths: string[] = [];
|
||||
const output = shortestRelativePaths(paths);
|
||||
expect(output).toEqual([]);
|
||||
});
|
||||
|
||||
it("should handle paths with same base names", () => {
|
||||
const paths = [
|
||||
"/a/b/c/d/file.txt",
|
||||
"/a/b/c/e/file.txt",
|
||||
"/a/b/f/g/h/file.txt",
|
||||
];
|
||||
const output = shortestRelativePaths(paths);
|
||||
expect(output).toEqual(["d/file.txt", "e/file.txt", "h/file.txt"]);
|
||||
});
|
||||
|
||||
it("should handle paths where entire path is needed", () => {
|
||||
const paths = ["/a/b/c/file.txt", "/a/b/c/file.txt", "/a/b/c/file.txt"];
|
||||
const output = shortestRelativePaths(paths);
|
||||
expect(output).toEqual(["file.txt", "file.txt", "file.txt"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("splitPath", () => {
|
||||
it("should split Unix-style paths", () => {
|
||||
const path = "/a/b/c/d/e.txt";
|
||||
const output = splitPath(path);
|
||||
expect(output).toEqual(["", "a", "b", "c", "d", "e.txt"]);
|
||||
});
|
||||
|
||||
it("should split Windows-style paths", () => {
|
||||
const path = "C:\\Users\\User\\Documents\\file.txt";
|
||||
const output = splitPath(path);
|
||||
expect(output).toEqual(["C:", "Users", "User", "Documents", "file.txt"]);
|
||||
});
|
||||
|
||||
it("should handle withRoot parameter", () => {
|
||||
const path = "/a/b/c/d/e.txt";
|
||||
const withRoot = "/a/b";
|
||||
const output = splitPath(path, withRoot);
|
||||
expect(output).toEqual(["b", "c", "d", "e.txt"]);
|
||||
});
|
||||
|
||||
it("should handle empty path", () => {
|
||||
const path = "";
|
||||
const output = splitPath(path);
|
||||
expect(output).toEqual([""]);
|
||||
});
|
||||
|
||||
it("should handle paths with multiple consecutive separators", () => {
|
||||
const path = "/a//b/c/d/e.txt";
|
||||
const output = splitPath(path);
|
||||
expect(output).toEqual(["", "a", "", "b", "c", "d", "e.txt"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getRelativePath", () => {
|
||||
it("should return the relative path with respect to workspace directories", () => {
|
||||
const filepath = "/workspace/project/src/file.ts";
|
||||
const workspaceDirs = ["/workspace/project"];
|
||||
const output = getRelativePath(filepath, workspaceDirs);
|
||||
expect(output).toBe("src/file.ts");
|
||||
});
|
||||
|
||||
it("should return the filename if not in any workspace", () => {
|
||||
const filepath = "/other/place/file.ts";
|
||||
const workspaceDirs = ["/workspace/project"];
|
||||
const output = getRelativePath(filepath, workspaceDirs);
|
||||
expect(output).toBe("file.ts");
|
||||
});
|
||||
|
||||
it("should handle multiple workspace directories", () => {
|
||||
const filepath = "/workspace2/project/src/file.ts";
|
||||
const workspaceDirs = ["/workspace/project", "/workspace2/project"];
|
||||
const output = getRelativePath(filepath, workspaceDirs);
|
||||
expect(output).toBe("src/file.ts");
|
||||
});
|
||||
|
||||
it("should handle Windows-style paths", () => {
|
||||
const filepath = "C:\\workspace\\project\\src\\file.ts";
|
||||
const workspaceDirs = ["C:\\workspace\\project"];
|
||||
const output = getRelativePath(filepath, workspaceDirs);
|
||||
expect(output).toBe("src/file.ts");
|
||||
});
|
||||
|
||||
it("should handle paths with spaces or special characters", () => {
|
||||
const filepath = "/workspace/project folder/src/file.ts";
|
||||
const workspaceDirs = ["/workspace/project folder"];
|
||||
const output = getRelativePath(filepath, workspaceDirs);
|
||||
expect(output).toBe("src/file.ts");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getMarkdownLanguageTagForFile", () => {
|
||||
it("should return correct language tag for known extensions", () => {
|
||||
expect(getMarkdownLanguageTagForFile("test.py")).toBe("python");
|
||||
|
|
|
|||
|
|
@ -66,131 +66,6 @@ export function dedentAndGetCommonWhitespace(s: string): [string, string] {
|
|||
return [lines.map((x) => x.replace(lcp, "")).join("\n"), lcp];
|
||||
}
|
||||
|
||||
const SEP_REGEX = /[\\/]/;
|
||||
|
||||
export function getBasename(filepath: string): string {
|
||||
return filepath.split(SEP_REGEX).pop() ?? "";
|
||||
}
|
||||
|
||||
export function getLastNPathParts(filepath: string, n: number): string {
|
||||
if (n <= 0) {
|
||||
return "";
|
||||
}
|
||||
return filepath.split(SEP_REGEX).slice(-n).join("/");
|
||||
}
|
||||
|
||||
export function groupByLastNPathParts(
|
||||
filepaths: string[],
|
||||
n: number,
|
||||
): Record<string, string[]> {
|
||||
return filepaths.reduce(
|
||||
(groups, item) => {
|
||||
const lastNParts = getLastNPathParts(item, n);
|
||||
if (!groups[lastNParts]) {
|
||||
groups[lastNParts] = [];
|
||||
}
|
||||
groups[lastNParts].push(item);
|
||||
return groups;
|
||||
},
|
||||
{} as Record<string, string[]>,
|
||||
);
|
||||
}
|
||||
|
||||
export function getUniqueFilePath(
|
||||
item: string,
|
||||
itemGroups: Record<string, string[]>,
|
||||
): string {
|
||||
const lastTwoParts = getLastNPathParts(item, 2);
|
||||
const group = itemGroups[lastTwoParts];
|
||||
|
||||
let n = 2;
|
||||
if (group.length > 1) {
|
||||
while (
|
||||
group.some(
|
||||
(otherItem) =>
|
||||
otherItem !== item &&
|
||||
getLastNPathParts(otherItem, n) === getLastNPathParts(item, n),
|
||||
)
|
||||
) {
|
||||
n++;
|
||||
}
|
||||
}
|
||||
|
||||
return getLastNPathParts(item, n);
|
||||
}
|
||||
|
||||
export function shortestRelativePaths(paths: string[]): string[] {
|
||||
if (paths.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const partsLengths = paths.map((x) => x.split(SEP_REGEX).length);
|
||||
const currentRelativePaths = paths.map(getBasename);
|
||||
const currentNumParts = paths.map(() => 1);
|
||||
const isDuplicated = currentRelativePaths.map(
|
||||
(x, i) =>
|
||||
currentRelativePaths.filter((y, j) => y === x && paths[i] !== paths[j])
|
||||
.length > 1,
|
||||
);
|
||||
|
||||
while (isDuplicated.some(Boolean)) {
|
||||
const firstDuplicatedPath = currentRelativePaths.find(
|
||||
(x, i) => isDuplicated[i],
|
||||
);
|
||||
if (!firstDuplicatedPath) {
|
||||
break;
|
||||
}
|
||||
|
||||
currentRelativePaths.forEach((x, i) => {
|
||||
if (x === firstDuplicatedPath) {
|
||||
currentNumParts[i] += 1;
|
||||
currentRelativePaths[i] = getLastNPathParts(
|
||||
paths[i],
|
||||
currentNumParts[i],
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
isDuplicated.forEach((x, i) => {
|
||||
if (x) {
|
||||
isDuplicated[i] =
|
||||
// Once we've used up all the parts, we can't make it longer
|
||||
currentNumParts[i] < partsLengths[i] &&
|
||||
currentRelativePaths.filter((y) => y === currentRelativePaths[i])
|
||||
.length > 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return currentRelativePaths;
|
||||
}
|
||||
|
||||
export function splitPath(path: string, withRoot?: string): string[] {
|
||||
let parts = path.includes("/") ? path.split("/") : path.split("\\");
|
||||
if (withRoot !== undefined) {
|
||||
const rootParts = splitPath(withRoot);
|
||||
parts = parts.slice(rootParts.length - 1);
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
export function getRelativePath(
|
||||
filepath: string,
|
||||
workspaceDirs: string[],
|
||||
): string {
|
||||
for (const workspaceDir of workspaceDirs) {
|
||||
const filepathParts = splitPath(filepath);
|
||||
const workspaceDirParts = splitPath(workspaceDir);
|
||||
if (
|
||||
filepathParts.slice(0, workspaceDirParts.length).join("/") ===
|
||||
workspaceDirParts.join("/")
|
||||
) {
|
||||
return filepathParts.slice(workspaceDirParts.length).join("/");
|
||||
}
|
||||
}
|
||||
return splitPath(filepath).pop() ?? ""; // If the file is not in any of the workspaces, return the plain filename
|
||||
}
|
||||
|
||||
export function getMarkdownLanguageTagForFile(filepath: string): string {
|
||||
const extToLangMap: { [key: string]: string } = {
|
||||
py: "python",
|
||||
|
|
|
|||
|
|
@ -1,13 +0,0 @@
|
|||
import { PlatformPath, posix, win32 } from "node:path";
|
||||
import { IDE } from "..";
|
||||
|
||||
export type PathSep = "/" | "\\";
|
||||
|
||||
function getPathModuleFromPathSep(pathSep: PathSep): PlatformPath {
|
||||
return pathSep === "/" ? posix : win32;
|
||||
}
|
||||
|
||||
export async function getPathModuleForIde(ide: IDE): Promise<PlatformPath> {
|
||||
const pathSep = await ide.pathSep();
|
||||
return getPathModuleFromPathSep(pathSep as PathSep);
|
||||
}
|
||||
21
core/util/pathToUri.ts
Normal file
21
core/util/pathToUri.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import { fileURLToPath, pathToFileURL } from "url";
|
||||
|
||||
import * as URI from "uri-js";
|
||||
|
||||
// CAN ONLY BE USED IN CORE
|
||||
|
||||
// Converts a local path to a file:// URI
|
||||
export function localPathToUri(path: string) {
|
||||
const url = pathToFileURL(path);
|
||||
return URI.normalize(url.toString());
|
||||
}
|
||||
|
||||
export function localPathOrUriToPath(localPathOrUri: string): string {
|
||||
try {
|
||||
return fileURLToPath(localPathOrUri);
|
||||
} catch (e) {
|
||||
// console.log("Received local filepath", localPathOrUri);
|
||||
|
||||
return localPathOrUri;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
import * as JSONC from "comment-json";
|
||||
import dotenv from "dotenv";
|
||||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
import { pathToFileURL } from "url";
|
||||
|
||||
import * as JSONC from "comment-json";
|
||||
import dotenv from "dotenv";
|
||||
|
||||
import { IdeType, SerializedContinueConfig } from "../";
|
||||
import { defaultConfig, defaultConfigJetBrains } from "../config/default";
|
||||
|
|
@ -45,9 +45,6 @@ export function getGlobalContinueIgnorePath(): string {
|
|||
return continueIgnorePath;
|
||||
}
|
||||
|
||||
/*
|
||||
Deprecated, replace with getContinueGlobalUri where possible
|
||||
*/
|
||||
export function getContinueGlobalPath(): string {
|
||||
// This is ~/.continue on mac/linux
|
||||
const continuePath = CONTINUE_GLOBAL_DIR;
|
||||
|
|
@ -57,10 +54,6 @@ export function getContinueGlobalPath(): string {
|
|||
return continuePath;
|
||||
}
|
||||
|
||||
export function getContinueGlobalUri(): string {
|
||||
return pathToFileURL(CONTINUE_GLOBAL_DIR).href;
|
||||
}
|
||||
|
||||
export function getSessionsFolderPath(): string {
|
||||
const sessionsPath = path.join(getContinueGlobalPath(), "sessions");
|
||||
if (!fs.existsSync(sessionsPath)) {
|
||||
|
|
@ -341,6 +334,15 @@ export function getLogsDirPath(): string {
|
|||
return logsPath;
|
||||
}
|
||||
|
||||
export function getLogFilePath(): string {
|
||||
const logFilePath = path.join(getContinueGlobalPath(), "continue.log");
|
||||
// Make sure the file/directory exist
|
||||
if (!fs.existsSync(logFilePath)) {
|
||||
fs.writeFileSync(logFilePath, "");
|
||||
}
|
||||
return logFilePath;
|
||||
}
|
||||
|
||||
export function getCoreLogsPath(): string {
|
||||
return path.join(getLogsDirPath(), "core.log");
|
||||
}
|
||||
|
|
@ -399,3 +401,13 @@ export function setupInitialDotContinueDirectory() {
|
|||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function getDiffsDirectoryPath(): string {
|
||||
const diffsPath = path.join(getContinueGlobalPath(), ".diffs"); // .replace(/^C:/, "c:"); ??
|
||||
if (!fs.existsSync(diffsPath)) {
|
||||
fs.mkdirSync(diffsPath, {
|
||||
recursive: true,
|
||||
});
|
||||
}
|
||||
return diffsPath;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import path from "path";
|
||||
|
||||
import Parser, { Language } from "web-tree-sitter";
|
||||
import { FileSymbolMap, IDE, SymbolWithRange } from "..";
|
||||
import { getUriFileExtension } from "./uri";
|
||||
|
||||
export enum LanguageName {
|
||||
CPP = "cpp",
|
||||
|
|
@ -145,7 +146,7 @@ export async function getLanguageForFile(
|
|||
): Promise<Language | undefined> {
|
||||
try {
|
||||
await Parser.init();
|
||||
const extension = path.extname(filepath).slice(1);
|
||||
const extension = getUriFileExtension(filepath);
|
||||
|
||||
const languageName = supportedLanguages[extension];
|
||||
if (!languageName) {
|
||||
|
|
@ -165,7 +166,8 @@ export async function getLanguageForFile(
|
|||
}
|
||||
|
||||
export const getFullLanguageName = (filepath: string) => {
|
||||
return supportedLanguages[filepath.split(".").pop() ?? ""];
|
||||
const extension = getUriFileExtension(filepath);
|
||||
return supportedLanguages[extension];
|
||||
};
|
||||
|
||||
export async function getQueryForFile(
|
||||
|
|
@ -226,7 +228,6 @@ export async function getSymbolsForFile(
|
|||
contents: string,
|
||||
): Promise<SymbolWithRange[] | undefined> {
|
||||
const parser = await getParserForFile(filepath);
|
||||
|
||||
if (!parser) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -286,7 +287,6 @@ export async function getSymbolsForFile(
|
|||
node.children.forEach(findNamedNodesRecursive);
|
||||
}
|
||||
findNamedNodesRecursive(tree.rootNode);
|
||||
|
||||
return symbols;
|
||||
}
|
||||
|
||||
|
|
|
|||
181
core/util/uri.test.ts
Normal file
181
core/util/uri.test.ts
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
// Generated by continue
|
||||
import * as URI from "uri-js";
|
||||
import {
|
||||
pathToUriPathSegment,
|
||||
findUriInDirs,
|
||||
relativePathOrUriToUri,
|
||||
getUriPathBasename,
|
||||
getUriFileExtension,
|
||||
getFileExtensionFromBasename,
|
||||
getLastNUriRelativePathParts,
|
||||
joinPathsToUri,
|
||||
getShortestUniqueRelativeUriPaths,
|
||||
getLastNPathParts,
|
||||
} from "./uri";
|
||||
|
||||
describe("uri utils", () => {
|
||||
describe("pathToUriPathSegment", () => {
|
||||
it("should convert Windows paths to URI segments", () => {
|
||||
expect(pathToUriPathSegment("\\path\\to\\folder\\")).toBe(
|
||||
"path/to/folder",
|
||||
);
|
||||
expect(pathToUriPathSegment("\\this\\is\\afile.ts")).toBe(
|
||||
"this/is/afile.ts",
|
||||
);
|
||||
});
|
||||
|
||||
it("should clean Unix paths", () => {
|
||||
expect(pathToUriPathSegment("/path/to/folder/")).toBe("path/to/folder");
|
||||
expect(pathToUriPathSegment("is/already/clean")).toBe("is/already/clean");
|
||||
});
|
||||
|
||||
it("should encode URI special characters", () => {
|
||||
expect(pathToUriPathSegment("path/with spaces/file")).toBe(
|
||||
"path/with%20spaces/file",
|
||||
);
|
||||
expect(pathToUriPathSegment("special#chars?in&path")).toBe(
|
||||
"special%23chars%3Fin%26path",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findUriInDirs", () => {
|
||||
const dirUris = [
|
||||
"file:///workspace/project1",
|
||||
"file:///workspace/project2",
|
||||
];
|
||||
|
||||
it("should find URI in directory", () => {
|
||||
const result = findUriInDirs(
|
||||
"file:///workspace/project1/src/file.ts",
|
||||
dirUris,
|
||||
);
|
||||
expect(result).toEqual({
|
||||
uri: "file:///workspace/project1/src/file.ts",
|
||||
relativePathOrBasename: "src/file.ts",
|
||||
foundInDir: "file:///workspace/project1",
|
||||
});
|
||||
});
|
||||
|
||||
it("should return basename when URI not in directories", () => {
|
||||
const result = findUriInDirs("file:///other/location/file.ts", dirUris);
|
||||
expect(result).toEqual({
|
||||
uri: "file:///other/location/file.ts",
|
||||
relativePathOrBasename: "file.ts",
|
||||
foundInDir: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("should throw error for invalid URIs", () => {
|
||||
expect(() => findUriInDirs("invalid-uri", dirUris)).toThrow(
|
||||
"Invalid uri: invalid-uri",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("URI path operations", () => {
|
||||
it("should get URI path basename", () => {
|
||||
expect(getUriPathBasename("file:///path/to/file.txt")).toBe("file.txt");
|
||||
expect(getUriPathBasename("file:///path/to/folder/")).toBe("folder");
|
||||
});
|
||||
|
||||
it("should get URI file extension", () => {
|
||||
expect(getUriFileExtension("file:///path/to/file.TXT")).toBe("txt");
|
||||
expect(getUriFileExtension("file:///path/to/file")).toBe("");
|
||||
});
|
||||
|
||||
it("should get file extension from basename", () => {
|
||||
expect(getFileExtensionFromBasename("file.txt")).toBe("txt");
|
||||
expect(getFileExtensionFromBasename("file")).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("joinPathsToUri", () => {
|
||||
it("should join paths to base URI", () => {
|
||||
expect(joinPathsToUri("file:///base", "path", "to", "file.txt")).toBe(
|
||||
"file:///base/path/to/file.txt",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle paths with special characters", () => {
|
||||
expect(
|
||||
joinPathsToUri("file:///base", "path with spaces", "file.txt"),
|
||||
).toBe("file:///base/path%20with%20spaces/file.txt");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getShortestUniqueRelativeUriPaths", () => {
|
||||
it("should find shortest unique paths", () => {
|
||||
const uris = [
|
||||
"file:///workspace/project1/src/components/Button.tsx",
|
||||
"file:///workspace/project1/src/utils/Button.tsx",
|
||||
];
|
||||
const dirUris = ["file:///workspace/project1"];
|
||||
|
||||
const result = getShortestUniqueRelativeUriPaths(uris, dirUris);
|
||||
expect(result).toEqual([
|
||||
{
|
||||
uri: "file:///workspace/project1/src/components/Button.tsx",
|
||||
uniquePath: "components/Button.tsx",
|
||||
},
|
||||
{
|
||||
uri: "file:///workspace/project1/src/utils/Button.tsx",
|
||||
uniquePath: "utils/Button.tsx",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getLastNPathParts", () => {
|
||||
it("should get last N parts of path", () => {
|
||||
expect(getLastNPathParts("path/to/some/file.txt", 2)).toBe(
|
||||
"some/file.txt",
|
||||
);
|
||||
expect(getLastNPathParts("path/to/some/file.txt", 0)).toBe("");
|
||||
});
|
||||
|
||||
it("should handle Windows paths", () => {
|
||||
expect(getLastNPathParts("path\\to\\some\\file.txt", 2)).toBe(
|
||||
"some/file.txt",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("relativePathOrUriToUri", () => {
|
||||
const consoleSpy = jest.spyOn(console, "trace").mockImplementation();
|
||||
|
||||
afterEach(() => {
|
||||
consoleSpy.mockClear();
|
||||
});
|
||||
|
||||
it("should return original URI if scheme exists", () => {
|
||||
const uri = "file:///path/to/file.txt";
|
||||
expect(relativePathOrUriToUri(uri, "file:///base")).toBe(uri);
|
||||
});
|
||||
|
||||
it("should convert relative path to URI", () => {
|
||||
expect(relativePathOrUriToUri("path/to/file.txt", "file:///base")).toBe(
|
||||
"file:///base/path/to/file.txt",
|
||||
);
|
||||
expect(consoleSpy).toHaveBeenCalledWith("Received path with no scheme");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getLastNUriRelativePathParts", () => {
|
||||
it("should get last N parts of URI relative path", () => {
|
||||
const dirUris = ["file:///workspace/project1"];
|
||||
const uri = "file:///workspace/project1/src/components/Button.tsx";
|
||||
|
||||
expect(getLastNUriRelativePathParts(dirUris, uri, 2)).toBe(
|
||||
"components/Button.tsx",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle URI not in directories", () => {
|
||||
const dirUris = ["file:///workspace/project1"];
|
||||
const uri = "file:///other/path/file.txt";
|
||||
|
||||
expect(getLastNUriRelativePathParts(dirUris, uri, 2)).toBe("file.txt");
|
||||
});
|
||||
});
|
||||
});
|
||||
190
core/util/uri.ts
Normal file
190
core/util/uri.ts
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
import * as URI from "uri-js";
|
||||
|
||||
/** Converts any OS path to cleaned up URI path segment format with no leading/trailing slashes
|
||||
e.g. \path\to\folder\ -> path/to/folder
|
||||
\this\is\afile.ts -> this/is/afile.ts
|
||||
is/already/clean -> is/already/clean
|
||||
**/
|
||||
|
||||
export function pathToUriPathSegment(path: string) {
|
||||
let clean = path.replace(/[\\]/g, "/"); // backslashes -> forward slashes
|
||||
clean = clean.replace(/^\//, ""); // remove start slash
|
||||
clean = clean.replace(/\/$/, ""); // remove end slash
|
||||
return clean
|
||||
.split("/")
|
||||
.map((segment) => encodeURIComponent(segment))
|
||||
.join("/");
|
||||
}
|
||||
|
||||
export function getCleanUriPath(uri: string) {
|
||||
const path = URI.parse(uri).path;
|
||||
if (!path) {
|
||||
return "";
|
||||
}
|
||||
return pathToUriPathSegment(path);
|
||||
}
|
||||
|
||||
export function findUriInDirs(
|
||||
uri: string,
|
||||
dirUriCandidates: string[],
|
||||
): {
|
||||
uri: string;
|
||||
relativePathOrBasename: string;
|
||||
foundInDir: string | null;
|
||||
} {
|
||||
const uriComps = URI.parse(uri);
|
||||
if (!uriComps.scheme) {
|
||||
throw new Error(`Invalid uri: ${uri}`);
|
||||
}
|
||||
for (const dir of dirUriCandidates) {
|
||||
const dirComps = URI.parse(dir);
|
||||
|
||||
if (!dirComps.scheme) {
|
||||
throw new Error(`Invalid uri: ${dir}`);
|
||||
}
|
||||
|
||||
if (uriComps.scheme !== dirComps.scheme) {
|
||||
continue;
|
||||
}
|
||||
// Can't just use startsWith because e.g.
|
||||
// file:///folder/file is not within file:///fold
|
||||
|
||||
// At this point we break the path up and check if each dir path part matches
|
||||
const dirPathParts = (dirComps.path ?? "")
|
||||
.replace(/^\//, "")
|
||||
.split("/")
|
||||
.map((part) => encodeURIComponent(part));
|
||||
const uriPathParts = (uriComps.path ?? "")
|
||||
.replace(/^\//, "")
|
||||
.split("/")
|
||||
.map((part) => encodeURIComponent(part));
|
||||
|
||||
if (uriPathParts.length < dirPathParts.length) {
|
||||
continue;
|
||||
}
|
||||
let allDirPartsMatch = true;
|
||||
for (let i = 0; i < dirPathParts.length; i++) {
|
||||
if (dirPathParts[i] !== uriPathParts[i]) {
|
||||
allDirPartsMatch = false;
|
||||
}
|
||||
}
|
||||
if (allDirPartsMatch) {
|
||||
const relativePath = uriPathParts.slice(dirPathParts.length).join("/");
|
||||
return {
|
||||
uri,
|
||||
relativePathOrBasename: relativePath,
|
||||
foundInDir: dir,
|
||||
};
|
||||
}
|
||||
}
|
||||
// Not found
|
||||
console.trace("Directory not found for uri", uri, dirUriCandidates);
|
||||
return {
|
||||
uri,
|
||||
relativePathOrBasename: getUriPathBasename(uri),
|
||||
foundInDir: null,
|
||||
};
|
||||
}
|
||||
|
||||
/*
|
||||
To smooth out the transition from path to URI will use this function to warn when path is used
|
||||
This will NOT work consistently with full OS paths like c:\blah\blah or ~/Users/etc
|
||||
*/
|
||||
export function relativePathOrUriToUri(
|
||||
relativePathOrUri: string,
|
||||
defaultDirUri: string,
|
||||
): string {
|
||||
const out = URI.parse(relativePathOrUri);
|
||||
if (out.scheme) {
|
||||
return relativePathOrUri;
|
||||
}
|
||||
console.trace("Received path with no scheme");
|
||||
return joinPathsToUri(defaultDirUri, out.path ?? "");
|
||||
}
|
||||
|
||||
/*
|
||||
Returns just the file or folder name of a URI
|
||||
*/
|
||||
export function getUriPathBasename(uri: string): string {
|
||||
const cleanPath = getCleanUriPath(uri);
|
||||
return cleanPath.split("/")?.pop() || "";
|
||||
}
|
||||
|
||||
export function getFileExtensionFromBasename(basename: string) {
|
||||
const parts = basename.split(".");
|
||||
if (parts.length < 2) {
|
||||
return "";
|
||||
}
|
||||
return (parts.slice(-1)[0] ?? "").toLowerCase();
|
||||
}
|
||||
|
||||
/*
|
||||
Returns the file extension of a URI
|
||||
*/
|
||||
export function getUriFileExtension(uri: string) {
|
||||
const baseName = getUriPathBasename(uri);
|
||||
return getFileExtensionFromBasename(baseName);
|
||||
}
|
||||
|
||||
export function getLastNUriRelativePathParts(
|
||||
dirUriCandidates: string[],
|
||||
uri: string,
|
||||
n: number,
|
||||
): string {
|
||||
const { relativePathOrBasename } = findUriInDirs(uri, dirUriCandidates);
|
||||
return getLastNPathParts(relativePathOrBasename, n);
|
||||
}
|
||||
|
||||
export function joinPathsToUri(uri: string, ...pathSegments: string[]) {
|
||||
const components = URI.parse(uri);
|
||||
const segments = pathSegments.map((segment) => pathToUriPathSegment(segment));
|
||||
components.path = `${components.path}/${segments.join("/")}`;
|
||||
return URI.serialize(components);
|
||||
}
|
||||
|
||||
export function getShortestUniqueRelativeUriPaths(
|
||||
uris: string[],
|
||||
dirUriCandidates: string[],
|
||||
): {
|
||||
uri: string;
|
||||
uniquePath: string;
|
||||
}[] {
|
||||
// Split all URIs into segments and count occurrences of each suffix combination
|
||||
const segmentCombinationsMap = new Map<string, number>();
|
||||
const segmentsInfo = uris.map((uri) => {
|
||||
const { relativePathOrBasename } = findUriInDirs(uri, dirUriCandidates);
|
||||
const cleanPath = pathToUriPathSegment(relativePathOrBasename);
|
||||
const segments = cleanPath.split("/");
|
||||
const suffixes: string[] = [];
|
||||
|
||||
// Generate all possible suffix combinations, starting from the shortest (basename)
|
||||
for (let i = segments.length - 1; i >= 0; i--) {
|
||||
const suffix = segments.slice(i).join("/");
|
||||
suffixes.push(suffix); // Now pushing in order from shortest to longest
|
||||
// Count occurrences of each suffix
|
||||
segmentCombinationsMap.set(
|
||||
suffix,
|
||||
(segmentCombinationsMap.get(suffix) || 0) + 1,
|
||||
);
|
||||
}
|
||||
|
||||
return { uri, segments, suffixes, cleanPath };
|
||||
});
|
||||
// Find shortest unique path for each URI
|
||||
return segmentsInfo.map(({ uri, suffixes, cleanPath }) => {
|
||||
// Since suffixes are now ordered from shortest to longest,
|
||||
// the first unique one we find will be the shortest
|
||||
const uniqueCleanPath =
|
||||
suffixes.find((suffix) => segmentCombinationsMap.get(suffix) === 1) ??
|
||||
cleanPath; // fallback to full path if no unique suffix found
|
||||
return { uri, uniquePath: decodeURIComponent(uniqueCleanPath) };
|
||||
});
|
||||
}
|
||||
// Only used when working with system paths and relative paths
|
||||
// Since doesn't account for URI segements before workspace
|
||||
export function getLastNPathParts(filepath: string, n: number): string {
|
||||
if (n <= 0) {
|
||||
return "";
|
||||
}
|
||||
return filepath.split(/[\\/]/).slice(-n).join("/");
|
||||
}
|
||||
|
|
@ -41,21 +41,34 @@ More models, functionalities and documentation will be added in the future for A
|
|||
|
||||
> We recommend to utilize the`OpenAI` or `Anthropic` models for the best performance and results for the `Chat` and `Edit` functionalities.
|
||||
|
||||
## Ask Sage Documentation
|
||||
Ask Sage documentation is not available with Continue.Dev, so if you have any questions or need help with Ask Sage type `@ask` and select the `Ask Sage` option in the chat. Then procced to ask your question about Ask Sage.
|
||||
|
||||
## Current Models From Ask Sage Supported
|
||||
|
||||
The current Models available provided by Ask Sage are:
|
||||
|
||||
| Model | Added |
|
||||
|--------------------|-------|
|
||||
| Gov GPT-4.0 | Yes |
|
||||
| Gov GPT-4o | Yes |
|
||||
| GPT-4o | Yes |
|
||||
| GPT-4o-mini | Yes |
|
||||
| GPT-3.5-16K | Yes |
|
||||
| Calude 3 Opus | Yes |
|
||||
| Calude 3 Sonet | Yes |
|
||||
| Calude 3.5 Sonnet | Yes |
|
||||
| Gemini Pro | Yes |
|
||||
| llama 3 | Yes |
|
||||
| Mistral Large | Yes |
|
||||
| Index | Model | Added | Status |
|
||||
|-------|------------------------|-------|--------|
|
||||
| 1 | GPT-4 Gov | Yes | ✅ |
|
||||
| 2 | GPT-4o Gov | Yes | ✅ |
|
||||
| 3 | GPT-4o-mini Gov | Yes | ✅ |
|
||||
| 4 | GPT-3.5-Turbo Gov | Yes | ✅ |
|
||||
| 5 | GPT-4o | Yes | ✅ |
|
||||
| 6 | GPT-4o-mini | Yes | ✅ |
|
||||
| 7 | GPT-4 | Yes | ✅ |
|
||||
| 8 | GPT-4-32K | Yes | ✅ |
|
||||
| 9 | GPT-o1 | Yes | ✅ |
|
||||
| 10 | GPT-o1-mini | Yes | ✅ |
|
||||
| 11 | GPT-3.5-turbo | Yes | ✅ |
|
||||
| 12 | Calude 3.5 Sonnet Gov | Yes | ✅ |
|
||||
| 13 | Calude 3 Opus | Yes | ✅ |
|
||||
| 14 | Calude 3 Sonet | Yes | ✅ |
|
||||
| 15 | Calude 3.5 Sonnet | Yes | ✅ |
|
||||
| 16 | Grok (xAI) | Yes | ✅ |
|
||||
| 17 | Groq Llama 3.3 | Yes | ✅ |
|
||||
| 18 | Groq 70B | Yes | ✅ |
|
||||
| 19 | Gemini Pro | Yes | ✅ |
|
||||
| 20 | llama 3 | Yes | ✅ |
|
||||
| 21 | Mistral Large | Yes | ✅ |
|
||||
|
||||
|
|
|
|||
|
|
@ -160,21 +160,24 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
|
|||
// Handle file changes and deletions - reindex
|
||||
connection.subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
|
||||
override fun after(events: List<VFileEvent>) {
|
||||
// Collect all relevant paths for deletions
|
||||
val deletedPaths = events.filterIsInstance<VFileDeleteEvent>()
|
||||
.map { event -> event.file.path.split("/").dropLast(1).joinToString("/") }
|
||||
// Collect all relevant URIs for deletions
|
||||
val deletedURIs = events.filterIsInstance<VFileDeleteEvent>()
|
||||
.map { event -> event.file.url }
|
||||
|
||||
// Collect all relevant paths for content changes
|
||||
val changedPaths = events.filterIsInstance<VFileContentChangeEvent>()
|
||||
.map { event -> event.file.path.split("/").dropLast(1).joinToString("/") }
|
||||
// Send "files/deleted" message if there are any deletions
|
||||
if (deletedURIs.isNotEmpty()) {
|
||||
val data = mapOf("files" to deletedURIs)
|
||||
continuePluginService.coreMessenger?.request("files/deleted", data, null) { _ -> }
|
||||
}
|
||||
|
||||
// Combine both lists of paths for re-indexing
|
||||
val allPaths = deletedPaths + changedPaths
|
||||
// Collect all relevant URIs for content changes
|
||||
val changedURIs = events.filterIsInstance<VFileContentChangeEvent>()
|
||||
.map { event -> event.file.url }
|
||||
|
||||
// Create a data map if there are any paths to re-index
|
||||
if (allPaths.isNotEmpty()) {
|
||||
val data = mapOf("files" to allPaths)
|
||||
continuePluginService.coreMessenger?.request("index/forceReIndexFiles", data, null) { _ -> }
|
||||
// Send "files/changed" message if there are any content changes
|
||||
if (changedURIs.isNotEmpty()) {
|
||||
val data = mapOf("files" to changedURIs)
|
||||
continuePluginService.coreMessenger?.request("files/changed", data, null) { _ -> }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
|
@ -217,12 +220,10 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
|
|||
// Reload the WebView
|
||||
continuePluginService?.let { pluginService ->
|
||||
val allModulePaths = ModuleManager.getInstance(project).modules
|
||||
.flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.map { it.path } }
|
||||
.map { Paths.get(it).normalize() }
|
||||
.flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.map { it.url } }
|
||||
|
||||
val topLevelModulePaths = allModulePaths
|
||||
.filter { modulePath -> allModulePaths.none { it != modulePath && modulePath.startsWith(it) } }
|
||||
.map { it.toString() }
|
||||
|
||||
pluginService.workspacePaths = topLevelModulePaths.toTypedArray()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -69,7 +69,7 @@ class AutocompleteService(private val project: Project) {
|
|||
val column = editor.caretModel.primaryCaret.logicalPosition.column
|
||||
val input = mapOf(
|
||||
"completionId" to completionId,
|
||||
"filepath" to virtualFile?.path,
|
||||
"filepath" to virtualFile?.url,
|
||||
"pos" to mapOf(
|
||||
"line" to editor.caretModel.primaryCaret.logicalPosition.line,
|
||||
"character" to column
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue