(BROKEN COMMI) path -> uri vscode utils and prompt files cont
This commit is contained in:
parent
a88915ec71
commit
b6b3cceb78
46 changed files with 738 additions and 792 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,4 +1,5 @@
|
|||
import { IDE } from "../../index";
|
||||
import { isUriWithinDirectory } from "../../util/uri";
|
||||
import { ContextRetrievalService } from "../context/ContextRetrievalService";
|
||||
import { GetLspDefinitionsFunction } from "../types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
|
@ -45,7 +46,7 @@ async function getIdeSnippets(
|
|||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
|
||||
return ideSnippets.filter((snippet) =>
|
||||
workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)),
|
||||
workspaceDirs.some((dir) => isUriWithinDirectory(snippet.filepath, dir)),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
// Fill in the middle prompts
|
||||
|
||||
import { CompletionOptions } from "../../index.js";
|
||||
import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js";
|
||||
import {
|
||||
getLastNUriRelativePathParts,
|
||||
shortestRelativeUriPaths,
|
||||
} from "../../util/uri.js";
|
||||
import {
|
||||
AutocompleteCodeSnippet,
|
||||
AutocompleteSnippet,
|
||||
|
|
@ -12,7 +15,7 @@ export interface AutocompleteTemplate {
|
|||
compilePrefixSuffix?: (
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
filepath: string,
|
||||
directoryUri: string,
|
||||
reponame: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
) => [string, string];
|
||||
|
|
@ -21,7 +24,7 @@ export interface AutocompleteTemplate {
|
|||
| ((
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
filepath: string,
|
||||
directoryUri: string,
|
||||
reponame: string,
|
||||
language: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
|
|
@ -64,12 +67,12 @@ const qwenCoderFimTemplate: AutocompleteTemplate = {
|
|||
},
|
||||
};
|
||||
|
||||
const codestralFimTemplate: AutocompleteTemplate = {
|
||||
template: "[SUFFIX]{{{suffix}}}[PREFIX]{{{prefix}}}",
|
||||
completionOptions: {
|
||||
stop: ["[PREFIX]", "[SUFFIX]"],
|
||||
},
|
||||
};
|
||||
// const codestralFimTemplate: AutocompleteTemplate = {
|
||||
// template: "[SUFFIX]{{{suffix}}}[PREFIX]{{{prefix}}}",
|
||||
// completionOptions: {
|
||||
// stop: ["[PREFIX]", "[SUFFIX]"],
|
||||
// },
|
||||
// };
|
||||
|
||||
const codestralMultifileFimTemplate: AutocompleteTemplate = {
|
||||
compilePrefixSuffix: (
|
||||
|
|
@ -81,12 +84,15 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
|
|||
): [string, string] => {
|
||||
if (snippets.length === 0) {
|
||||
if (suffix.trim().length === 0 && prefix.trim().length === 0) {
|
||||
return [`+++++ ${getLastNPathParts(filepath, 2)}\n${prefix}`, suffix];
|
||||
return [
|
||||
`+++++ ${getLastNUriRelativePathParts(filepath, 2)}\n${prefix}`,
|
||||
suffix,
|
||||
];
|
||||
}
|
||||
return [prefix, suffix];
|
||||
}
|
||||
|
||||
const relativePaths = shortestRelativePaths([
|
||||
const relativePaths = shortestRelativeUriPaths([
|
||||
...snippets.map((snippet) =>
|
||||
"filepath" in snippet ? snippet.filepath : "Untitled.txt",
|
||||
),
|
||||
|
|
@ -133,38 +139,38 @@ 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[],
|
||||
): string => {
|
||||
const otherFiles =
|
||||
snippets.length === 0
|
||||
? ""
|
||||
: `<file_sep>${snippets
|
||||
.map((snippet) => {
|
||||
return snippet.content;
|
||||
})
|
||||
.join("<file_sep>")}<file_sep>`;
|
||||
// // 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[],
|
||||
// ): string => {
|
||||
// const otherFiles =
|
||||
// snippets.length === 0
|
||||
// ? ""
|
||||
// : `<file_sep>${snippets
|
||||
// .map((snippet) => {
|
||||
// return snippet.content;
|
||||
// })
|
||||
// .join("<file_sep>")}<file_sep>`;
|
||||
|
||||
const prompt = `${otherFiles}<fim_prefix>${prefix}<fim_suffix>${suffix}<fim_middle>`;
|
||||
return prompt;
|
||||
},
|
||||
completionOptions: {
|
||||
stop: [
|
||||
"<fim_prefix>",
|
||||
"<fim_suffix>",
|
||||
"<fim_middle>",
|
||||
"<file_sep>",
|
||||
"<|endoftext|>",
|
||||
],
|
||||
},
|
||||
};
|
||||
// const prompt = `${otherFiles}<fim_prefix>${prefix}<fim_suffix>${suffix}<fim_middle>`;
|
||||
// return prompt;
|
||||
// },
|
||||
// completionOptions: {
|
||||
// stop: [
|
||||
// "<fim_prefix>",
|
||||
// "<fim_suffix>",
|
||||
// "<fim_middle>",
|
||||
// "<file_sep>",
|
||||
// "<|endoftext|>",
|
||||
// ],
|
||||
// },
|
||||
// };
|
||||
|
||||
const codeLlamaFimTemplate: AutocompleteTemplate = {
|
||||
template: "<PRE> {{{prefix}}} <SUF>{{{suffix}}} <MID>",
|
||||
|
|
@ -191,7 +197,7 @@ const codegeexFimTemplate: AutocompleteTemplate = {
|
|||
template: (
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
filepath: string,
|
||||
directoryUri: string,
|
||||
reponame: string,
|
||||
language: string,
|
||||
allSnippets: AutocompleteSnippet[],
|
||||
|
|
@ -200,10 +206,10 @@ const codegeexFimTemplate: AutocompleteTemplate = {
|
|||
(snippet) => snippet.type === AutocompleteSnippetType.Code,
|
||||
) as AutocompleteCodeSnippet[];
|
||||
|
||||
const relativePaths = shortestRelativePaths([
|
||||
...snippets.map((snippet) => snippet.filepath),
|
||||
filepath,
|
||||
]);
|
||||
const relativePaths = shortestRelativeUriPaths(
|
||||
[...snippets.map((snippet) => snippet.filepath)],
|
||||
directoryUri,
|
||||
);
|
||||
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,
|
||||
|
|
@ -39,7 +39,7 @@ const formatCodeSnippet = (
|
|||
): AutocompleteCodeSnippet => {
|
||||
return {
|
||||
...snippet,
|
||||
content: `Path: ${getLastNPathParts(snippet.filepath, 2)}\n${snippet.content}`,
|
||||
content: `Path: ${getLastNUriRelativePathParts(snippet.filepath, 2)}\n${snippet.content}`,
|
||||
};
|
||||
};
|
||||
|
||||
|
|
@ -49,10 +49,6 @@ const formatDiffSnippet = (
|
|||
return snippet;
|
||||
};
|
||||
|
||||
const getCurrentFilepath = (helper: HelperVars) => {
|
||||
return getLastNPathParts(helper.filepath, 2);
|
||||
};
|
||||
|
||||
const commentifySnippet = (
|
||||
helper: HelperVars,
|
||||
snippet: AutocompleteSnippet,
|
||||
|
|
@ -68,7 +64,7 @@ export const formatSnippets = (
|
|||
snippets: AutocompleteSnippet[],
|
||||
): string => {
|
||||
const currentFilepathComment = addCommentMarks(
|
||||
getCurrentFilepath(helper),
|
||||
getLastNUriRelativePathParts(helper.filepath, 2),
|
||||
helper,
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -1,14 +1,13 @@
|
|||
import { IDE } from "..";
|
||||
import * as uri from "../util/uri";
|
||||
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 = uri.join(dir, SYSTEM_PROMPT_DOT_FILE);
|
||||
const dotFile = joinPathsToUri(dir, SYSTEM_PROMPT_DOT_FILE);
|
||||
if (await ide.fileExists(dotFile)) {
|
||||
try {
|
||||
const content = await ide.readFile(dotFile);
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ 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 {
|
||||
|
|
@ -19,7 +18,7 @@ import type {
|
|||
|
||||
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
|
||||
|
||||
export async function getPromptFiles(
|
||||
async function getPromptFilesFromDir(
|
||||
ide: IDE,
|
||||
dir: string,
|
||||
): Promise<{ path: string; content: string }[]> {
|
||||
|
|
@ -31,8 +30,9 @@ export async function getPromptFiles(
|
|||
}
|
||||
|
||||
const paths = await walkDir(dir, ide, { ignoreFiles: [] });
|
||||
const results = paths.map(async (path) => {
|
||||
const content = await ide.readFile(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 };
|
||||
});
|
||||
return Promise.all(results);
|
||||
|
|
@ -42,244 +42,273 @@ export async function getPromptFiles(
|
|||
}
|
||||
}
|
||||
|
||||
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(
|
||||
export async function getAllPromptFilesV2(
|
||||
ide: IDE,
|
||||
promptPath: string | undefined,
|
||||
): Promise<void> {
|
||||
overridePromptFolder?: string,
|
||||
): Promise<{ path: string; content: string }[]> {
|
||||
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",
|
||||
);
|
||||
let promptFiles: { path: string; content: string }[] = [];
|
||||
|
||||
await ide.writeFile(promptFilePath, DEFAULT_PROMPT_FILE);
|
||||
await ide.openFile(promptFilePath);
|
||||
}
|
||||
promptFiles = (
|
||||
await Promise.all(
|
||||
workspaceDirs.map((dir) =>
|
||||
getPromptFilesFromDir(
|
||||
ide,
|
||||
joinPathsToUri(dir, overridePromptFolder ?? ".continue/prompts"),
|
||||
),
|
||||
),
|
||||
)
|
||||
).flat();
|
||||
|
||||
export function slashCommandFromPromptFile(
|
||||
path: string,
|
||||
content: string,
|
||||
): SlashCommand | null {
|
||||
const { name, description, systemMessage, prompt, version } = parsePromptFile(
|
||||
path,
|
||||
content,
|
||||
);
|
||||
// Also read from ~/.continue/.prompts
|
||||
promptFiles.push(...readAllGlobalPromptFiles());
|
||||
|
||||
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,
|
||||
return await Promise.all(
|
||||
promptFiles.map(async (file) => {
|
||||
const content = await ide.readFile(file.path);
|
||||
return { path: file.path, content };
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
// 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 }}}
|
||||
|
||||
items.forEach((item) =>
|
||||
context.addContextItem(createContextItem(item, provider)),
|
||||
);
|
||||
// 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
|
||||
|
||||
return items.map((item) => item.content).join("\n\n");
|
||||
},
|
||||
]);
|
||||
}
|
||||
// Here is an example. The example is surrounded in backticks, but your response should not be:
|
||||
|
||||
function createContextItem(item: ContextItem, provider: IContextProvider) {
|
||||
return {
|
||||
...item,
|
||||
id: {
|
||||
itemId: item.description,
|
||||
providerTitle: provider.description.title,
|
||||
},
|
||||
};
|
||||
}
|
||||
// \`\`\`
|
||||
// ### ✅ <Filename1>
|
||||
|
||||
function updateChatHistory(
|
||||
history: ChatMessage[],
|
||||
commandName: string,
|
||||
renderedPrompt: string,
|
||||
systemMessage?: string,
|
||||
) {
|
||||
const messages = [...history];
|
||||
// ### ❌ <Filename2>
|
||||
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const message = messages[i];
|
||||
const { role, content } = message;
|
||||
if (role !== "user") {
|
||||
continue;
|
||||
}
|
||||
// <Description>
|
||||
// \`\`\`
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
// You should look primarily for the following types of issues, and only mention other problems if they are highly pressing.
|
||||
|
||||
if (systemMessage) {
|
||||
messages[0]?.role === "system"
|
||||
? (messages[0].content = systemMessage)
|
||||
: messages.unshift({ role: "system", content: systemMessage });
|
||||
}
|
||||
// - console.logs that have been left after debugging
|
||||
// - repeated code
|
||||
// - algorithmic errors that could fail under edge cases
|
||||
// - something that could be refactored
|
||||
|
||||
return messages;
|
||||
}
|
||||
// Make sure to review ALL files that were changed, do not skip any.
|
||||
// `;
|
||||
|
||||
function updateArrayContent(
|
||||
message: any,
|
||||
commandName: string,
|
||||
renderedPrompt: string,
|
||||
) {
|
||||
return {
|
||||
...message,
|
||||
content: message.content.map((part: any) =>
|
||||
part.text?.startsWith(`/${commandName}`)
|
||||
? { ...part, text: renderedPrompt }
|
||||
: part,
|
||||
),
|
||||
};
|
||||
}
|
||||
// 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,
|
||||
// ),
|
||||
// };
|
||||
// }
|
||||
|
|
|
|||
|
|
@ -488,7 +488,6 @@ declare global {
|
|||
|
||||
// Callbacks
|
||||
onDidChangeActiveTextEditor(callback: (filepath: string) => void): void;
|
||||
pathSep(): Promise<string>;
|
||||
}
|
||||
|
||||
// Slash Commands
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import {
|
|||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../";
|
||||
import { getAllPromptFilesV2 } from "../../promptFiles/v2/getPromptFiles";
|
||||
import { parsePreamble } from "../../promptFiles/v2/parse";
|
||||
import { renderPromptFileV2 } from "../../promptFiles/v2/renderPromptFile";
|
||||
|
||||
|
|
@ -38,7 +37,7 @@ class PromptFilesContextProvider extends BaseContextProvider {
|
|||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const promptFiles = await getAllPromptFilesV2(
|
||||
const promptFiles = await getAllPromptFiles(
|
||||
args.ide,
|
||||
args.config.experimental?.promptPath,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -71,8 +71,6 @@ 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]
|
||||
|
|
|
|||
|
|
@ -112,13 +112,12 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
...results
|
||||
.sort((a, b) => a.filepath.localeCompare(b.filepath))
|
||||
.map((r) => {
|
||||
const name = `${getUriPathBasename(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 {
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import {
|
|||
RefreshIndexResults,
|
||||
} from "./types.js";
|
||||
import { walkDirAsync } from "./walkDir.js";
|
||||
import { 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(),
|
||||
|
|
@ -224,7 +221,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}...`,
|
||||
|
|
@ -456,10 +453,4 @@ export class CodebaseIndexer {
|
|||
}
|
||||
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];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -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[] = [];
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -25,13 +25,6 @@ async function expectPaths(
|
|||
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) {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
import path from "path";
|
||||
|
||||
import { IDE } from "../..";
|
||||
|
||||
import { DEFAULT_PROMPTS_FOLDER } from ".";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
|
||||
const DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
|
||||
# It is used to define and reuse prompts within Continue
|
||||
|
|
@ -48,7 +47,7 @@ export async function createNewPromptFile(
|
|||
"No workspace directories found. Make sure you've opened a folder in your IDE.",
|
||||
);
|
||||
}
|
||||
const promptFilePath = path.join(
|
||||
const promptFilePath = joinPathsToUri(
|
||||
workspaceDirs[0],
|
||||
promptPath ?? DEFAULT_PROMPTS_FOLDER,
|
||||
"new-prompt-file.prompt",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { createNewPromptFile } from "./createNewPromptFile";
|
||||
import { getPromptFiles } from "./getPromptFiles";
|
||||
import { getPromptFilesV1 } from "./getPromptFiles";
|
||||
import { slashCommandFromPromptFile } from "./slashCommandFromPromptFile";
|
||||
|
||||
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
|
||||
|
||||
export { createNewPromptFile, getPromptFiles, slashCommandFromPromptFile };
|
||||
export { createNewPromptFile, getPromptFilesV1, slashCommandFromPromptFile };
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import * as YAML from "yaml";
|
||||
|
||||
import { ContinueSDK, SlashCommand } from "../..";
|
||||
import { getBasename } from "../../util/index";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
|
||||
import { getContextProviderHelpers } from "./getContextProviderHelpers";
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { IDE } from "../..";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
// import { getPathModuleForIde } from "../../util/pathModule";
|
||||
|
||||
const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
|
||||
|
|
@ -45,11 +46,10 @@ 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
|
||||
|
|
@ -57,7 +57,10 @@ export async function createNewPromptFileV2(
|
|||
let promptFileUri: string;
|
||||
do {
|
||||
const suffix = counter === 0 ? "" : `-${counter}`;
|
||||
promptFileUri = pathModule.join(baseDir, `new-prompt-file${suffix}.prompt`);
|
||||
promptFileUri = joinPathsToUri(
|
||||
baseDiruri,
|
||||
`new-prompt-file${suffix}.prompt`,
|
||||
);
|
||||
counter++;
|
||||
} while (await ide.fileExists(promptFileUri));
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { IDE } from "../..";
|
||||
import { walkDir } from "../../indexing/walkDir";
|
||||
import { getPathModuleForIde } from "../../util/pathModule";
|
||||
import { readAllGlobalPromptFiles } from "../../util/paths";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
|
||||
async function getPromptFilesFromDir(
|
||||
ide: IDE,
|
||||
|
|
@ -15,7 +15,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 };
|
||||
});
|
||||
|
|
@ -32,23 +33,17 @@ export async function getAllPromptFilesV2(
|
|||
): Promise<{ path: string; content: string }[]> {
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
let promptFiles: { path: string; content: string }[] = [];
|
||||
const pathModule = await getPathModuleForIde(ide);
|
||||
|
||||
promptFiles = (
|
||||
await Promise.all(
|
||||
workspaceDirs.map((dir) =>
|
||||
getPromptFilesFromDir(
|
||||
ide,
|
||||
pathModule.join(
|
||||
dir,
|
||||
overridePromptFolder ?? pathModule.join(".continue", "prompts"),
|
||||
),
|
||||
joinPathsToUri(dir, overridePromptFolder ?? ".continue/prompts"),
|
||||
),
|
||||
),
|
||||
)
|
||||
)
|
||||
.flat()
|
||||
.filter(({ path }) => path.endsWith(".prompt"));
|
||||
).flat();
|
||||
|
||||
// Also read from ~/.continue/.prompts
|
||||
promptFiles.push(...readAllGlobalPromptFiles());
|
||||
|
|
|
|||
|
|
@ -1,7 +1,5 @@
|
|||
import * as YAML from "yaml";
|
||||
|
||||
import { getBasename } from "../../util";
|
||||
|
||||
export function extractName(preamble: { name?: string }, path: string): string {
|
||||
return preamble.name ?? getBasename(path).split(".prompt")[0];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import { ContextItem, ContextProviderExtras } from "../..";
|
||||
import { contextProviderClassFromName } from "../../context/providers";
|
||||
import URLContextProvider from "../../context/providers/URLContextProvider";
|
||||
import { getBasename } from "../../util";
|
||||
import { resolveRelativePathInWorkspace } from "../../util/ideUtils";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
import { getPreambleAndBody } from "./parse";
|
||||
|
||||
async function resolveAttachment(
|
||||
|
|
@ -25,9 +26,19 @@ async function resolveAttachment(
|
|||
}
|
||||
|
||||
// Files
|
||||
if (await extras.ide.fileExists(name)) {
|
||||
const content = `\`\`\`${name}\n${await extras.ide.readFile(name)}\n\`\`\``;
|
||||
return [{ name: getBasename(name), content, description: name }];
|
||||
const resolvedFileUri = await resolveRelativePathInWorkspace(
|
||||
name,
|
||||
extras.ide,
|
||||
);
|
||||
if (resolvedFileUri) {
|
||||
const content = `\`\`\`${name}\n${await extras.ide.readFile(resolvedFileUri)}\n\`\`\``;
|
||||
return [
|
||||
{
|
||||
name: getUriPathBasename(resolvedFileUri),
|
||||
content,
|
||||
description: resolvedFileUri,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// URLs
|
||||
|
|
|
|||
|
|
@ -100,7 +100,6 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
ControlPlaneSessionInfo | undefined,
|
||||
];
|
||||
logoutOfControlPlane: [undefined, void];
|
||||
pathSep: [undefined, string];
|
||||
};
|
||||
|
||||
export type ToWebviewOrCoreFromIdeProtocol = {
|
||||
|
|
|
|||
|
|
@ -189,8 +189,5 @@ export class ReverseMessageIde {
|
|||
this.on("getBranch", (data) => {
|
||||
return this.ide.getBranch(data.dir);
|
||||
});
|
||||
this.on("pathSep", (data) => {
|
||||
return this.ide.pathSep();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -5,17 +5,17 @@ import { ToolImpl } from ".";
|
|||
|
||||
export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => {
|
||||
const { directory_path } = args;
|
||||
const absolutePath = await resolveRelativePathInWorkspace(
|
||||
const absoluteUri = await resolveRelativePathInWorkspace(
|
||||
directory_path,
|
||||
extras.ide,
|
||||
);
|
||||
|
||||
if (!absolutePath) {
|
||||
if (!absoluteUri) {
|
||||
throw new Error(`Directory path "${directory_path}" does not exist.`);
|
||||
}
|
||||
|
||||
const repoMap = await generateRepoMap(extras.llm, extras.ide, {
|
||||
dirs: [absolutePath],
|
||||
dirs: [absoluteUri],
|
||||
});
|
||||
return [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
|
||||
import {
|
||||
ContinueRcJson,
|
||||
|
|
@ -28,9 +27,6 @@ class FileSystemIde implements IDE {
|
|||
): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
pathSep(): Promise<string> {
|
||||
return Promise.resolve(path.sep);
|
||||
}
|
||||
fileExists(filepath: string): Promise<boolean> {
|
||||
return Promise.resolve(fs.existsSync(filepath));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ describe("resolveRelativePathInWorkspace", () => {
|
|||
|
||||
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);
|
||||
|
|
@ -24,7 +23,6 @@ describe("resolveRelativePathInWorkspace", () => {
|
|||
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")
|
||||
|
|
@ -38,7 +36,6 @@ describe("resolveRelativePathInWorkspace", () => {
|
|||
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);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,21 +1,49 @@
|
|||
import { IDE } from "..";
|
||||
import { pathToUriPathSegment } from "./uri";
|
||||
|
||||
/*
|
||||
This function takes a relative filepath
|
||||
And checks each workspace for if it exists or not
|
||||
Only returns fully resolved URI if it exists
|
||||
*/
|
||||
export async function resolveRelativePathInWorkspace(
|
||||
path: string,
|
||||
ide: IDE,
|
||||
): Promise<string | undefined> {
|
||||
const pathSep = await ide.pathSep();
|
||||
if (path.startsWith(pathSep)) {
|
||||
return path;
|
||||
}
|
||||
|
||||
const cleanPath = pathToUriPathSegment(path);
|
||||
const workspaces = await ide.getWorkspaceDirs();
|
||||
for (const workspace of workspaces) {
|
||||
const fullPath = `${workspace}${pathSep}${path}`;
|
||||
if (await ide.fileExists(fullPath)) {
|
||||
return fullPath;
|
||||
const fullUri = `${workspace}/${cleanPath}`;
|
||||
if (await ide.fileExists(fullUri)) {
|
||||
return fullUri;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/*
|
||||
This function takes a relative filepath (which may not exist)
|
||||
And, based on which workspace has the closest matching path
|
||||
Guesses which workspace and returns resolved URI
|
||||
|
||||
Original use case of for tools trying to create new files
|
||||
If no meaninful path match just concatenates to first workspace's uri
|
||||
*/
|
||||
export async function inferResolvedUriFromRelativePath(
|
||||
path: string,
|
||||
ide: IDE,
|
||||
): Promise<string> {
|
||||
const cleanPath = pathToUriPathSegment(path);
|
||||
|
||||
const
|
||||
const workspaces = await ide.getWorkspaceDirs();
|
||||
for (const workspace of workspaces) {
|
||||
const fullUri = `${workspace}/${cleanPath}`;
|
||||
if (await ide.fileExists(fullUri)) {
|
||||
return fullUri;
|
||||
}
|
||||
}
|
||||
// console.warn("No meaninful filepath inferred from relative path " + path)
|
||||
return `${workspaces[0]}/${cleanPath}`
|
||||
}
|
||||
|
|
@ -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");
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
import fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
// import fs from "node:fs";
|
||||
|
||||
import Parser, { Language } from "web-tree-sitter";
|
||||
import { FileSymbolMap, IDE, SymbolWithRange } from "..";
|
||||
import { getUriFileExtension } from "./uri";
|
||||
|
||||
export enum LanguageName {
|
||||
CPP = "cpp",
|
||||
|
|
@ -145,7 +145,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 +165,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(
|
||||
|
|
|
|||
233
core/util/uri.test.ts
Normal file
233
core/util/uri.test.ts
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
import {
|
||||
getLastNUriRelativePathParts,
|
||||
getRelativePath,
|
||||
getUniqueUriPath,
|
||||
getUriPathBasename,
|
||||
groupByLastNPathParts,
|
||||
splitUriPath,
|
||||
} from "./uri";
|
||||
|
||||
describe("getUriPathBasename", () => {
|
||||
it("should return the base name of a Unix-style path", () => {
|
||||
const filepath = "/home/user/documents/file.txt";
|
||||
const output = getUriPathBasename(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 = getUriPathBasename(filepath);
|
||||
expect(output).toBe("file.txt");
|
||||
});
|
||||
|
||||
it("should handle paths with mixed separators", () => {
|
||||
const filepath = "C:/Users\\User/Documents/file.txt";
|
||||
const output = getUriPathBasename(filepath);
|
||||
expect(output).toBe("file.txt");
|
||||
});
|
||||
|
||||
it("should return an empty string for empty input", () => {
|
||||
const filepath = "";
|
||||
const output = getUriPathBasename(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("getUniqueUriPath", () => {
|
||||
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 = getUniqueUriPath(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 = getUniqueUriPath(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 = getUniqueUriPath(item, itemGroups);
|
||||
expect(output).toBe("d/e/file.txt");
|
||||
});
|
||||
});
|
||||
|
||||
describe("splitUriPath", () => {
|
||||
it("should split Unix-style paths", () => {
|
||||
const path = "/a/b/c/d/e.txt";
|
||||
const output = splitUriPath(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 = splitUriPath(path);
|
||||
expect(output).toEqual(["C:", "Users", "User", "Documents", "file.txt"]);
|
||||
});
|
||||
|
||||
it("should handle empty path", () => {
|
||||
const path = "";
|
||||
const output = splitUriPath(path);
|
||||
expect(output).toEqual([""]);
|
||||
});
|
||||
|
||||
it("should handle paths with multiple consecutive separators", () => {
|
||||
const path = "/a//b/c/d/e.txt";
|
||||
const output = splitUriPath(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("getLastNPathParts", () => {
|
||||
test("returns the last N parts of a filepath with forward slashes", () => {
|
||||
const filepath = "home/user/documents/project/file.txt";
|
||||
expect(getLastNUriRelativePathParts(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("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"]);
|
||||
});
|
||||
});
|
||||
|
|
@ -9,6 +9,17 @@ export function getFullPath(uri: string): string {
|
|||
}
|
||||
}
|
||||
|
||||
export function pathToUriPathSegment(path: string) {
|
||||
// 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
|
||||
let clean = path.replace(/[\\]/g, "/"); // backslashes -> forward slashes
|
||||
clean = clean.replace(/^\//, ""); // remove start slash
|
||||
clean = clean.replace(/\/$/, ""); // remove end slash
|
||||
return clean;
|
||||
}
|
||||
|
||||
// Whenever working with partial URIs
|
||||
// Should always first get the path relative to the workspaces
|
||||
// If a matching workspace is not found, ONLY the file name should be used
|
||||
|
|
@ -41,8 +52,11 @@ export function getUriPathBasename(uri: string): string {
|
|||
return getPath();
|
||||
}
|
||||
|
||||
export function join(uri: string, pathSegment: string) {
|
||||
return uri.replace(/\/*$/, "") + "/" + segment.replace(/^\/*/, "");
|
||||
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 groupByLastNPathParts(
|
||||
|
|
@ -59,7 +73,10 @@ export function getUniqueUriPath(
|
|||
return "hi";
|
||||
}
|
||||
|
||||
export function shortestRelativeUriPaths(uris: string[]): string[] {
|
||||
export function shortestRelativeUriPaths(
|
||||
uris: string[],
|
||||
directory: string,
|
||||
): string[] {
|
||||
if (uris.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,7 +46,6 @@ class MessageTypes {
|
|||
"applyToFile",
|
||||
"getGitHubAuthToken",
|
||||
"setGitHubAuthToken",
|
||||
"pathSep",
|
||||
"getControlPlaneSessionInfo",
|
||||
"logoutOfControlPlane",
|
||||
"getTerminalContents",
|
||||
|
|
|
|||
|
|
@ -391,7 +391,6 @@ class IdeProtocolClient(
|
|||
respond(null)
|
||||
}
|
||||
|
||||
"setSuggestionsLocked" -> {}
|
||||
"getSessionId" -> {}
|
||||
|
||||
"getLastModified" -> {
|
||||
|
|
@ -766,10 +765,6 @@ class IdeProtocolClient(
|
|||
respond(null)
|
||||
}
|
||||
|
||||
"pathSep" -> {
|
||||
respond(File.separator)
|
||||
}
|
||||
|
||||
else -> {}
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
|
|
|
|||
|
|
@ -17,12 +17,9 @@ import { executeGotoProvider } from "./autocomplete/lsp";
|
|||
import { DiffManager } from "./diff/horizontal";
|
||||
import { Repository } from "./otherExtensions/git";
|
||||
import { VsCodeIdeUtils } from "./util/ideUtils";
|
||||
import {
|
||||
getExtensionUri,
|
||||
openEditorAndRevealRange,
|
||||
uriFromFilePath,
|
||||
} from "./util/vscode";
|
||||
import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode";
|
||||
import { VsCodeWebviewProtocol } from "./webviewProtocol";
|
||||
import URI from "uri-js";
|
||||
|
||||
import type {
|
||||
ContinueRcJson,
|
||||
|
|
@ -48,12 +45,8 @@ class VsCodeIde implements IDE {
|
|||
this.ideUtils = new VsCodeIdeUtils();
|
||||
}
|
||||
|
||||
pathSep(): Promise<string> {
|
||||
return Promise.resolve(this.ideUtils.path.sep);
|
||||
}
|
||||
async fileExists(filepath: string): Promise<boolean> {
|
||||
const absPath = await this.ideUtils.resolveAbsFilepathInWorkspace(filepath);
|
||||
return vscode.workspace.fs.stat(uriFromFilePath(absPath)).then(
|
||||
async fileExists(uri: string): Promise<boolean> {
|
||||
return vscode.workspace.fs.stat(vscode.Uri.parse(uri)).then(
|
||||
() => true,
|
||||
() => false,
|
||||
);
|
||||
|
|
@ -437,7 +430,7 @@ class VsCodeIde implements IDE {
|
|||
|
||||
private static MAX_BYTES = 100000;
|
||||
|
||||
async readFile(filepath: string): Promise<string> {
|
||||
async readFile(fileUri: string): Promise<string> {
|
||||
try {
|
||||
filepath = this.ideUtils.getAbsolutePath(filepath);
|
||||
const uri = uriFromFilePath(filepath);
|
||||
|
|
@ -445,8 +438,8 @@ class VsCodeIde implements IDE {
|
|||
// First, check whether it's a notebook document
|
||||
// Need to iterate over the cells to get full contents
|
||||
const notebook =
|
||||
vscode.workspace.notebookDocuments.find(
|
||||
(doc) => doc.uri.toString() === uri.toString(),
|
||||
vscode.workspace.notebookDocuments.find((doc) =>
|
||||
URI.equal(doc.uri.toString(), uri.toString()),
|
||||
) ??
|
||||
(uri.fsPath.endsWith("ipynb")
|
||||
? await vscode.workspace.openNotebookDocument(uri)
|
||||
|
|
@ -507,7 +500,7 @@ class VsCodeIde implements IDE {
|
|||
}
|
||||
return {
|
||||
isUntitled: vscode.window.activeTextEditor.document.isUntitled,
|
||||
path: vscode.window.activeTextEditor.document.uri.fsPath,
|
||||
path: vscode.window.activeTextEditor.document.uri.toString(),
|
||||
contents: vscode.window.activeTextEditor.document.getText(),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import * as vscode from "vscode";
|
||||
|
||||
import { openEditorAndRevealRange, translate } from "./util/vscode";
|
||||
import URI from "uri-js"
|
||||
|
||||
export interface SuggestionRanges {
|
||||
oldRange: vscode.Range;
|
||||
|
|
@ -58,7 +59,7 @@ export function rerenderDecorations(editorUri: string) {
|
|||
const suggestions = editorToSuggestions.get(editorUri);
|
||||
const idx = currentSuggestion.get(editorUri);
|
||||
const editor = vscode.window.visibleTextEditors.find(
|
||||
(editor) => editor.document.uri.toString() === editorUri,
|
||||
(editor) => URI.equal(editor.document.uri.toString(), editorUri)
|
||||
);
|
||||
if (!suggestions || !editor) {
|
||||
return;
|
||||
|
|
@ -299,7 +300,7 @@ export async function rejectSuggestionCommand(
|
|||
}
|
||||
|
||||
export async function showSuggestion(
|
||||
editorFilename: string,
|
||||
editorUri: string,
|
||||
range: vscode.Range,
|
||||
suggestion: string,
|
||||
): Promise<boolean> {
|
||||
|
|
@ -312,7 +313,7 @@ export async function showSuggestion(
|
|||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
const editor = await openEditorAndRevealRange(editorFilename, range);
|
||||
const editor = await openEditorAndRevealRange(editorUri, range);
|
||||
if (!editor) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
|
@ -339,19 +340,19 @@ export async function showSuggestion(
|
|||
);
|
||||
const content = editor!.document.getText(suggestionRange);
|
||||
|
||||
const filename = editor!.document.uri.toString();
|
||||
if (editorToSuggestions.has(filename)) {
|
||||
const suggestions = editorToSuggestions.get(filename)!;
|
||||
const uriString = editor!.document.uri.toString();
|
||||
if (editorToSuggestions.has(uriString)) {
|
||||
const suggestions = editorToSuggestions.get(uriString)!;
|
||||
suggestions.push({
|
||||
oldRange: range,
|
||||
newRange: suggestionRange,
|
||||
newSelected: true,
|
||||
newContent: content,
|
||||
});
|
||||
editorToSuggestions.set(filename, suggestions);
|
||||
currentSuggestion.set(filename, suggestions.length - 1);
|
||||
editorToSuggestions.set(uriString, suggestions);
|
||||
currentSuggestion.set(uriString, suggestions.length - 1);
|
||||
} else {
|
||||
editorToSuggestions.set(filename, [
|
||||
editorToSuggestions.set(uriString, [
|
||||
{
|
||||
oldRange: range,
|
||||
newRange: suggestionRange,
|
||||
|
|
@ -359,10 +360,10 @@ export async function showSuggestion(
|
|||
newContent: content,
|
||||
},
|
||||
]);
|
||||
currentSuggestion.set(filename, 0);
|
||||
currentSuggestion.set(uriString, 0);
|
||||
}
|
||||
|
||||
rerenderDecorations(filename);
|
||||
rerenderDecorations(uriString);
|
||||
}
|
||||
resolve(success);
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,9 +1,7 @@
|
|||
import path from "node:path";
|
||||
|
||||
import { EXTENSION_NAME } from "core/control-plane/env";
|
||||
import _ from "lodash";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import URI from "uri-js";
|
||||
import { threadStopped } from "../debug/debug";
|
||||
import { VsCodeExtension } from "../extension/VsCodeExtension";
|
||||
import { GitExtension, Repository } from "../otherExtensions/git";
|
||||
|
|
@ -26,48 +24,47 @@ export class VsCodeIdeUtils {
|
|||
visibleMessages: Set<string> = new Set();
|
||||
|
||||
async gotoDefinition(
|
||||
uri: string,
|
||||
uri: vscode.Uri,
|
||||
position: vscode.Position,
|
||||
): Promise<vscode.Location[]> {
|
||||
const locations: vscode.Location[] = await vscode.commands.executeCommand(
|
||||
"vscode.executeDefinitionProvider",
|
||||
uriFromFilePath(filepath),
|
||||
uri,
|
||||
position,
|
||||
);
|
||||
return locations;
|
||||
}
|
||||
|
||||
async documentSymbol(filepath: string): Promise<vscode.DocumentSymbol[]> {
|
||||
async documentSymbol(uri: vscode.Uri): Promise<vscode.DocumentSymbol[]> {
|
||||
return await vscode.commands.executeCommand(
|
||||
"vscode.executeDocumentSymbolProvider",
|
||||
uriFromFilePath(filepath),
|
||||
uri,
|
||||
);
|
||||
}
|
||||
|
||||
async references(
|
||||
filepath: string,
|
||||
uri: vscode.Uri,
|
||||
position: vscode.Position,
|
||||
): Promise<vscode.Location[]> {
|
||||
return await vscode.commands.executeCommand(
|
||||
"vscode.executeReferenceProvider",
|
||||
uriFromFilePath(filepath),
|
||||
uri,
|
||||
position,
|
||||
);
|
||||
}
|
||||
|
||||
async foldingRanges(filepath: string): Promise<vscode.FoldingRange[]> {
|
||||
async foldingRanges(uri: vscode.Uri): Promise<vscode.FoldingRange[]> {
|
||||
return await vscode.commands.executeCommand(
|
||||
"vscode.executeFoldingRangeProvider",
|
||||
uriFromFilePath(filepath),
|
||||
uri,
|
||||
);
|
||||
}
|
||||
|
||||
private _workspaceDirectories: string[] | undefined = undefined;
|
||||
getWorkspaceDirectories(): string[] {
|
||||
private _workspaceDirectories: vscode.Uri[] | undefined = undefined;
|
||||
getWorkspaceDirectories(): vscode.Uri[] {
|
||||
if (this._workspaceDirectories === undefined) {
|
||||
this._workspaceDirectories =
|
||||
vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath) ||
|
||||
[];
|
||||
vscode.workspace.workspaceFolders?.map((folder) => folder.uri) || [];
|
||||
}
|
||||
|
||||
return this._workspaceDirectories;
|
||||
|
|
@ -135,37 +132,19 @@ export class VsCodeIdeUtils {
|
|||
);
|
||||
}
|
||||
|
||||
async resolveAbsFilepathInWorkspace(filepath: string): Promise<string> {
|
||||
// If the filepath is already absolute, return it as is
|
||||
if (this.path.isAbsolute(filepath)) {
|
||||
return filepath;
|
||||
}
|
||||
|
||||
// Try to resolve for each workspace directory
|
||||
const workspaceDirectories = this.getWorkspaceDirectories();
|
||||
for (const dir of workspaceDirectories) {
|
||||
const resolvedPath = this.path.resolve(dir, filepath);
|
||||
if (await this.fileExists(resolvedPath)) {
|
||||
return resolvedPath;
|
||||
}
|
||||
}
|
||||
|
||||
return filepath;
|
||||
}
|
||||
|
||||
async openFile(filepath: string, range?: vscode.Range) {
|
||||
async openFile(uri: vscode.Uri, range?: vscode.Range) {
|
||||
// vscode has a builtin open/get open files
|
||||
return await openEditorAndRevealRange(
|
||||
await this.resolveAbsFilepathInWorkspace(filepath),
|
||||
uri,
|
||||
range,
|
||||
vscode.ViewColumn.One,
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
async fileExists(filepath: string): Promise<boolean> {
|
||||
async fileExists(uri: vscode.Uri): Promise<boolean> {
|
||||
try {
|
||||
await vscode.workspace.fs.stat(uriFromFilePath(filepath));
|
||||
await vscode.workspace.fs.stat(uri);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
|
|
@ -186,11 +165,6 @@ export class VsCodeIdeUtils {
|
|||
});
|
||||
}
|
||||
|
||||
setSuggestionsLocked(filepath: string, locked: boolean) {
|
||||
editorSuggestionsLocked.set(filepath, locked);
|
||||
// TODO: Rerender?
|
||||
}
|
||||
|
||||
async getUserSecret(key: string) {
|
||||
// Check if secret already exists in VS Code settings (global)
|
||||
let secret = vscode.workspace.getConfiguration(EXTENSION_NAME).get(key);
|
||||
|
|
@ -243,7 +217,7 @@ export class VsCodeIdeUtils {
|
|||
.flat()
|
||||
.filter(Boolean) // filter out undefined values
|
||||
.filter((uri) => this.documentIsCode(uri)) // Filter out undesired documents
|
||||
.map((uri) => uri.fsPath);
|
||||
.map((uri) => uri.toString());
|
||||
}
|
||||
|
||||
getVisibleFiles(): string[] {
|
||||
|
|
@ -254,11 +228,11 @@ export class VsCodeIdeUtils {
|
|||
});
|
||||
}
|
||||
|
||||
saveFile(filepath: string) {
|
||||
saveFile(uri: vscode.Uri) {
|
||||
vscode.window.visibleTextEditors
|
||||
.filter((editor) => this.documentIsCode(editor.document.uri))
|
||||
.forEach((editor) => {
|
||||
if (editor.document.uri.fsPath === filepath) {
|
||||
if (URI.equal(editor.document.uri, uri.toString())) {
|
||||
editor.document.save();
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import * as path from "node:path";
|
||||
|
||||
import { machineIdSync } from "node-machine-id";
|
||||
import * as vscode from "vscode";
|
||||
import URI from "uri-js";
|
||||
|
||||
export function translate(range: vscode.Range, lines: number): vscode.Range {
|
||||
return new vscode.Range(
|
||||
|
|
@ -27,13 +26,13 @@ export function getExtensionUri(): vscode.Uri {
|
|||
}
|
||||
|
||||
export function getViewColumnOfFile(
|
||||
filepath: string,
|
||||
uri: vscode.Uri,
|
||||
): vscode.ViewColumn | undefined {
|
||||
for (const tabGroup of vscode.window.tabGroups.all) {
|
||||
for (const tab of tabGroup.tabs) {
|
||||
if (
|
||||
(tab?.input as any)?.uri &&
|
||||
(tab.input as any).uri.fsPath === filepath
|
||||
URI.equal((tab.input as any).uri, uri.toString())
|
||||
) {
|
||||
return tabGroup.viewColumn;
|
||||
}
|
||||
|
|
@ -71,20 +70,13 @@ export function getRightViewColumn(): vscode.ViewColumn {
|
|||
let showTextDocumentInProcess = false;
|
||||
|
||||
export function openEditorAndRevealRange(
|
||||
editorFilename: string,
|
||||
uri: vscode.Uri,
|
||||
range?: vscode.Range,
|
||||
viewColumn?: vscode.ViewColumn,
|
||||
preview?: boolean,
|
||||
): Promise<vscode.TextEditor> {
|
||||
return new Promise((resolve, _) => {
|
||||
let filename = editorFilename;
|
||||
if (editorFilename.startsWith("~")) {
|
||||
filename = path.join(
|
||||
process.env.HOME || process.env.USERPROFILE || "",
|
||||
editorFilename.slice(1),
|
||||
);
|
||||
}
|
||||
vscode.workspace.openTextDocument(filename).then(async (doc) => {
|
||||
vscode.workspace.openTextDocument(uri).then(async (doc) => {
|
||||
try {
|
||||
// An error is thrown mysteriously if you open two documents in parallel, hence this
|
||||
while (showTextDocumentInProcess) {
|
||||
|
|
@ -97,7 +89,7 @@ export function openEditorAndRevealRange(
|
|||
showTextDocumentInProcess = true;
|
||||
vscode.window
|
||||
.showTextDocument(doc, {
|
||||
viewColumn: getViewColumnOfFile(editorFilename) || viewColumn,
|
||||
viewColumn: getViewColumnOfFile(uri) || viewColumn,
|
||||
preview,
|
||||
})
|
||||
.then((editor) => {
|
||||
|
|
@ -114,33 +106,6 @@ export function openEditorAndRevealRange(
|
|||
});
|
||||
}
|
||||
|
||||
function windowsToPosix(windowsPath: string): string {
|
||||
let posixPath = windowsPath.split("\\").join("/");
|
||||
if (posixPath[1] === ":") {
|
||||
posixPath = posixPath.slice(2);
|
||||
}
|
||||
// posixPath = posixPath.replace(" ", "\\ ");
|
||||
return posixPath;
|
||||
}
|
||||
|
||||
function isWindowsLocalButNotRemote(): boolean {
|
||||
return (
|
||||
vscode.env.remoteName !== undefined &&
|
||||
[
|
||||
"wsl",
|
||||
"ssh-remote",
|
||||
"dev-container",
|
||||
"attached-container",
|
||||
"tunnel",
|
||||
].includes(vscode.env.remoteName) &&
|
||||
process.platform === "win32"
|
||||
);
|
||||
}
|
||||
|
||||
export function getPathSep(): string {
|
||||
return isWindowsLocalButNotRemote() ? "/" : path.sep;
|
||||
}
|
||||
|
||||
export function getUniqueId() {
|
||||
const id = vscode.env.machineId;
|
||||
if (id === "someValue.machineId") {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue