path -> uri continued

This commit is contained in:
Dallin Romney 2024-12-11 19:15:32 -08:00
parent ad52a7eab3
commit 25329bbd77
36 changed files with 211 additions and 312 deletions

View file

@ -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(
@ -55,7 +53,7 @@ export async function testAutocompleteFiltering(
const character = prefix.split("\n")[line].length;
const autocompleteInput: AutocompleteInput = {
completionId: "test-completion-id",
filepath,
filepath: fileUri,
pos: {
line,
character,

View file

@ -15,7 +15,7 @@ export interface AutocompleteTemplate {
compilePrefixSuffix?: (
prefix: string,
suffix: string,
directoryUri: string,
filepath: string,
reponame: string,
snippets: AutocompleteSnippet[],
) => [string, string];
@ -24,7 +24,7 @@ export interface AutocompleteTemplate {
| ((
prefix: string,
suffix: string,
directoryUri: string,
filepath: string,
reponame: string,
language: string,
snippets: AutocompleteSnippet[],
@ -85,7 +85,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
if (snippets.length === 0) {
if (suffix.trim().length === 0 && prefix.trim().length === 0) {
return [
`+++++ ${getLastNUriRelativePathParts(filepath, 2)}\n${prefix}`,
`+++++ ${getLastNUriRelativePathParts(workspaceDirs, filepath, 2)}\n${prefix}`,
suffix,
];
}

View file

@ -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";
@ -13,6 +12,7 @@ import { getStopTokens } from "./getStopTokens";
import { SnippetPayload } from "../snippets";
import { formatSnippets } from "./formatting";
import { getSnippets } from "./filtering";
import { getUriPathBasename } from "../../util/uri";
function getTemplate(helper: HelperVars): AutocompleteTemplate {
if (helper.options.template) {
@ -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({
@ -63,7 +63,7 @@ export function renderPrompt({
let prefix = helper.input.manuallyPassPrefix || helper.prunedPrefix;
let suffix = helper.input.manuallyPassPrefix ? "" : helper.prunedSuffix;
const reponame = getBasename(workspaceDirs[0] ?? "myproject");
const reponame = getUriPathBasename(workspaceDirs[0] ?? "myproject");
const { template, compilePrefixSuffix, completionOptions } =
getTemplate(helper);

View file

@ -1,15 +1,18 @@
import * as fs from "fs/promises";
import * as path from "path";
import ignore from "ignore";
import { IDE, SlashCommand } from "../..";
import { FileType, IDE, SlashCommand } from "../..";
import {
defaultIgnoreDir,
defaultIgnoreFile,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "../../indexing/ignore";
import { renderChatMessage } from "../../util/messageContent";
import {
getRelativePath,
getUriPathBasename,
joinPathsToUri,
} from "../../util/uri";
const LANGUAGE_DEP_MGMT_FILENAMES = [
"package.json", // JavaScript (Node.js)
@ -55,27 +58,32 @@ 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) => !ig.ignores(entry.name));
const workspaceDirs = await ide.getWorkspaceDirs();
return filteredEntries;
const withRelativePaths = entries.map((entry) => ({
uri: entry[0],
type: entry[1],
basename: getUriPathBasename(entry[0]),
relativePath: getRelativePath(entry[0], workspaceDirs),
}));
return withRelativePaths.filter((entry) => !ig.ignores(entry.relativePath));
}
async function gatherProjectContext(
@ -83,7 +91,6 @@ async function gatherProjectContext(
ide: IDE,
): Promise<string> {
let context = "";
async function exploreDirectory(dir: string, currentDepth: number = 0) {
if (currentDepth > MAX_EXPLORE_DEPTH) {
return;
@ -92,19 +99,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 === 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`;
}
}
}

View file

@ -1,10 +1,9 @@
import * as fs from "node:fs";
import { homedir } from "node:os";
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 +61,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);

View file

@ -59,3 +59,7 @@ export function ctxItemToRifWithContents(
return rif;
}
// export function codeContextItemToMarkdownSource(
// item: ContextItemWithId,
// ): string {}

View file

@ -446,7 +446,6 @@ declare global {
fileExists(filepath: 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>;
runCommand(command: string): Promise<void>;
saveFile(filepath: string): Promise<void>;

View file

@ -6,6 +6,7 @@ import {
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../";
import { getAllPromptFilesV2 } from "../../promptFiles/v2/getPromptFiles";
import { parsePreamble } from "../../promptFiles/v2/parse";
import { renderPromptFileV2 } from "../../promptFiles/v2/renderPromptFile";
@ -37,7 +38,7 @@ class PromptFilesContextProvider extends BaseContextProvider {
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const promptFiles = await getAllPromptFiles(
const promptFiles = await getAllPromptFilesV2(
args.ide,
args.config.experimental?.promptPath,
);

View file

@ -71,6 +71,7 @@ This is the question that you should select relevant files for: "${input}"`;
return [];
}
const subDirPrefix = filterDirectory ? filterDirectory + pathSep : "";
const files =
content
.split("<results>")[1]

View file

@ -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);

2
core/index.d.ts vendored
View file

@ -617,8 +617,6 @@ export interface IDE {
showVirtualFile(title: string, contents: string): Promise<void>;
getContinueDir(): Promise<string>;
openFile(path: string): Promise<void>;
openUrl(url: string): Promise<void>;

View file

@ -1,7 +1,8 @@
import * as YAML from "yaml";
import { getLastNPathParts } from "../../util";
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] {

View file

@ -26,7 +26,6 @@ export type ToIdeFromWebviewOrCoreProtocol = {
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];

View file

@ -138,17 +138,6 @@ export class MessageIde implements IDE {
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(fileUri: string, contents: string): Promise<void> {
await this.request("writeFile", { path: fileUri, contents });
}

View file

@ -126,10 +126,6 @@ export class ReverseMessageIde {
return undefined;
});
this.on("getContinueDir", () => {
return this.ide.getContinueDir();
});
this.on("writeFile", (data) => {
return this.ide.writeFile(data.path, data.contents);
});

View file

@ -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 [
{

View file

@ -186,10 +186,6 @@ class FileSystemIde implements IDE {
return Promise.resolve();
}
getContinueDir(): Promise<string> {
return Promise.resolve(getContinueGlobalPath());
}
openFile(path: string): Promise<void> {
return Promise.resolve();
}

View file

@ -119,52 +119,6 @@ export function getLastNPathParts(filepath: string, n: number): string {
// 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(getB);
// 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] = getLastNUriRelativePathParts(
// 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) {

View file

@ -321,6 +321,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");
}
@ -379,3 +388,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;
}

View file

@ -1,4 +1,5 @@
// import fs from "node:fs";
import fs from "node:fs";
import path from "path";
import Parser, { Language } from "web-tree-sitter";
import { FileSymbolMap, IDE, SymbolWithRange } from "..";

View file

@ -89,6 +89,10 @@ export function getUriPathBasename(uri: string): string {
return getPath();
}
export function getFileExtensionFromBasename(filename: string) {
return filename.split(".").pop() ?? "";
}
export function joinPathsToUri(uri: string, ...pathSegments: string[]) {
const components = URI.parse(uri);
const segments = pathSegments.map((segment) => pathToUriPathSegment(segment));

View file

@ -19,7 +19,6 @@ class MessageTypes {
"getWorkspaceDirs",
"showLines",
"listFolders",
"getContinueDir",
"writeFile",
"fileExists",
"showVirtualFile",

View file

@ -560,10 +560,6 @@ class IdeProtocolClient(
respond(file.exists())
}
"getContinueDir" -> {
respond(getContinueGlobalPath())
}
"openFile" -> {
setFileOpen((data as Map<String, Any>)["path"] as String)
respond(null)

View file

@ -373,10 +373,6 @@ class VsCodeIde implements IDE {
return this.ideUtils.getWorkspaceDirectories().map((uri) => uri.toString());
}
async getContinueDir(): Promise<string> {
return getContinueGlobalPath();
}
async writeFile(fileUri: string, contents: string): Promise<void> {
await vscode.workspace.fs.writeFile(
vscode.Uri.parse(fileUri),
@ -441,7 +437,7 @@ class VsCodeIde implements IDE {
vscode.workspace.notebookDocuments.find((doc) =>
URI.equal(doc.uri.toString(), uri.toString()),
) ??
(uri.fsPath.endsWith("ipynb")
(uri.path.endsWith("ipynb")
? await vscode.workspace.openNotebookDocument(uri)
: undefined);
if (notebook) {

View file

@ -1,7 +1,5 @@
/* eslint-disable @typescript-eslint/naming-convention */
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { ContextMenuConfig, RangeInFileWithContents } from "core";
import { CompletionProvider } from "core/autocomplete/CompletionProvider";
@ -12,7 +10,11 @@ import { EXTENSION_NAME } from "core/control-plane/env";
import { Core } from "core/core";
import { walkDirAsync } from "core/indexing/walkDir";
import { GlobalContext } from "core/util/GlobalContext";
import { getConfigJsonPath, getDevDataFilePath } from "core/util/paths";
import {
getConfigJsonPath,
getDevDataFilePath,
getLogFilePath,
} from "core/util/paths";
import { Telemetry } from "core/util/posthog";
import readLastLines from "read-last-lines";
import * as vscode from "vscode";
@ -160,17 +162,17 @@ async function addHighlightedCodeToContext(
}
async function addEntireFileToContext(
filepath: vscode.Uri,
uri: vscode.Uri,
webviewProtocol: VsCodeWebviewProtocol | undefined,
) {
// If a directory, add all files in the directory
const stat = await vscode.workspace.fs.stat(filepath);
const stat = await vscode.workspace.fs.stat(uri);
if (stat.type === vscode.FileType.Directory) {
const files = await vscode.workspace.fs.readDirectory(filepath);
const files = await vscode.workspace.fs.readDirectory(uri);
for (const [filename, type] of files) {
if (type === vscode.FileType.File) {
addEntireFileToContext(
vscode.Uri.joinPath(filepath, filename),
vscode.Uri.joinPath(uri, filename),
webviewProtocol,
);
}
@ -179,9 +181,9 @@ async function addEntireFileToContext(
}
// Get the contents of the file
const contents = (await vscode.workspace.fs.readFile(filepath)).toString();
const contents = (await vscode.workspace.fs.readFile(uri)).toString();
const rangeInFileWithContents = {
filepath: filepath.toString(),
filepath: uri.toString(),
contents: contents,
range: {
start: {
@ -230,12 +232,12 @@ async function processDiff(
diffManager: DiffManager,
ide: VsCodeIde,
verticalDiffManager: VerticalDiffManager,
newFileUri?: vscode.Uri,
newFileUri?: string,
streamId?: string,
) {
captureCommandTelemetry(`${action}Diff`);
let newOrCurrentUri = newFileUri?.toString();
let newOrCurrentUri = newFileUri;
if (!newOrCurrentUri) {
const currentFile = await ide.getCurrentFile();
newOrCurrentUri = currentFile?.path;
@ -343,24 +345,18 @@ const getCommandsMap: (
);
}
return {
"continue.acceptDiff": async (
newFilepath?: string | vscode.Uri,
streamId?: string,
) =>
"continue.acceptDiff": async (newFileUri?: string, streamId?: string) =>
processDiff(
"accept",
sidebar,
diffManager,
ide,
verticalDiffManager,
newFilepath,
newFileUri,
streamId,
),
"continue.rejectDiff": async (
newFilepath?: string | vscode.Uri,
streamId?: string,
) =>
"continue.rejectDiff": async (newFilepath?: string, streamId?: string) =>
processDiff(
"reject",
sidebar,
@ -626,17 +622,8 @@ const getCommandsMap: (
},
"continue.viewLogs": async () => {
captureCommandTelemetry("viewLogs");
// Open ~/.continue/continue.log
const logFile = path.join(os.homedir(), ".continue", "continue.log");
// Make sure the file/directory exist
if (!fs.existsSync(logFile)) {
fs.mkdirSync(path.dirname(logFile), { recursive: true });
fs.writeFileSync(logFile, "");
}
const uri = vscode.Uri.file(logFile);
await vscode.window.showTextDocument(uri);
const logFilePath = getLogFilePath();
await vscode.window.showTextDocument(vscode.Uri.file(logFilePath));
},
"continue.debugTerminal": async () => {
captureCommandTelemetry("debugTerminal");
@ -783,9 +770,9 @@ const getCommandsMap: (
.stat(uri)
?.then((stat) => stat.type === vscode.FileType.Directory);
if (isDirectory) {
for await (const filepath of walkDirAsync(uri.toString(), ide)) {
for await (const fileUri of walkDirAsync(uri.toString(), ide)) {
addEntireFileToContext(
vscode.Uri.parse(filepath),
vscode.Uri.parse(fileUri),
sidebar.webviewProtocol,
);
}
@ -917,7 +904,7 @@ const getCommandsMap: (
} else if (
selectedOption === "$(gear) Configure autocomplete options"
) {
ide.openFile(getConfigJsonPath());
ide.openFile(vscode.Uri.file(getConfigJsonPath()).toString());
} else if (
autocompleteModels.some((model) => model.title === selectedOption)
) {

View file

@ -1,7 +1,3 @@
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { devDataPath } from "core/util/paths";
import * as vscode from "vscode";
@ -17,47 +13,34 @@ interface DiffInfo {
range: vscode.Range;
}
async function readFile(uri: vscode.Uri): Promise<string> {
async function readFile(fileUri: string): Promise<string> {
return await vscode.workspace.fs
.readFile(uri)
.readFile(vscode.Uri.parse(fileUri))
.then((bytes) => new TextDecoder().decode(bytes));
}
async function writeFile(uri: vscode.Uri, contents: string) {
await vscode.workspace.fs.writeFile(uri, new TextEncoder().encode(contents));
async function writeFile(fileUri: string, contents: string) {
await vscode.workspace.fs.writeFile(
vscode.Uri.parse(fileUri),
new TextEncoder().encode(contents),
);
}
// THIS IS LOCAL
export const DIFF_DIRECTORY = path
.join(os.homedir(), ".continue", ".diffs")
.replace(/^C:/, "c:");
export class DiffManager {
// Create a temporary file in the global .continue directory which displays the updated version
// Doing this because virtual files are read-only
private diffs: Map<string, DiffInfo> = new Map();
diffAtNewFilepath(newFilepath: string): DiffInfo | undefined {
return this.diffs.get(newFilepath);
}
private async setupDirectory() {
// Make sure the diff directory exists
if (!fs.existsSync(DIFF_DIRECTORY)) {
fs.mkdirSync(DIFF_DIRECTORY, {
recursive: true,
});
}
diffAtNewFilepath(newFileUri: string): DiffInfo | undefined {
return this.diffs.get(newFileUri);
}
webviewProtocol: VsCodeWebviewProtocol | undefined;
constructor(private readonly extensionContext: vscode.ExtensionContext) {
this.setupDirectory();
// Listen for file closes, and if it's a diff file, clean up
vscode.workspace.onDidCloseTextDocument((document) => {
const newFilepath = document.uri.fsPath;
const newFilepath = document.uri.toString();
const diffInfo = this.diffs.get(newFilepath);
if (diffInfo) {
this.cleanUpDiff(diffInfo, false);
@ -73,15 +56,15 @@ export class DiffManager {
}
private remoteTmpDir = "/tmp/continue";
private getNewFilepath(originalFilepath: string): string {
private getNewFileUri(originalFileUri: string): vscode.Uri {
if (vscode.env.remoteName) {
// If we're in a remote, use the remote's temp directory
// Doing this because there's no easy way to find the home directory,
// and there aren't write permissions to the root directory
// and writing these to local causes separate issues
// because the vscode.diff command will always try to read from remote
vscode.workspace.fs.createDirectory(uriFromFilePath(this.remoteTmpDir));
return path.join(
vscode.workspace.fs.createDirectory(vscode.Uri.file(this.remoteTmpDir));
return vscode.Uri.j.join(
this.remoteTmpDir,
this.escapeFilepath(originalFilepath),
);
@ -160,8 +143,6 @@ export class DiffManager {
newContent: string,
step_index: number,
): Promise<string> {
await this.setupDirectory();
// Create or update existing diff
const newFilepath = this.getNewFilepath(originalFilepath);
await writeFile(uriFromFilePath(newFilepath), newContent);

View file

@ -159,7 +159,7 @@ export class VsCodeExtension {
const { verticalDiffCodeLens } = registerAllCodeLensProviders(
context,
this.diffManager,
this.verticalDiffManager.filepathToCodeLens,
this.verticalDiffManager.fileUriToCodeLens,
config,
);
@ -182,7 +182,7 @@ export class VsCodeExtension {
registerAllCodeLensProviders(
context,
this.diffManager,
this.verticalDiffManager.filepathToCodeLens,
this.verticalDiffManager.fileUriToCodeLens,
newConfig,
);
}
@ -264,8 +264,8 @@ export class VsCodeExtension {
vscode.workspace.onDidSaveTextDocument(async (event) => {
this.core.invoke("files/changed", {
uris: [event.uri.toString()]
})
uris: [event.uri.toString()],
});
});
vscode.workspace.onDidDeleteFiles(async (event) => {
@ -317,7 +317,7 @@ export class VsCodeExtension {
// Refresh index when branch is changed
this.ide.getWorkspaceDirs().then((dirs) =>
dirs.forEach(async (dir) => {
const repo = await this.ide.getRepo(vscode.Uri.file(dir));
const repo = await this.ide.getRepo(dir);
if (repo) {
repo.state.onDidChange(() => {
// args passed to this callback are always undefined, so keep track of previous branch

View file

@ -1,5 +1,4 @@
import * as fs from "node:fs";
import * as path from "node:path";
import { ConfigHandler } from "core/config/ConfigHandler";
import { getModelByRole } from "core/config/util";
@ -30,6 +29,7 @@ import { getExtensionUri } from "../util/vscode";
import { VsCodeIde } from "../VsCodeIde";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
import { getUriPathBasename } from "core/util/uri";
import { showTutorial } from "../util/tutorial";
/**
* A shared messenger class between Core and Webview
@ -86,22 +86,16 @@ export class VsCodeMessenger {
) {
/** WEBVIEW ONLY LISTENERS **/
this.onWebview("showFile", (msg) => {
const fullPath = getFullyQualifiedPath(this.ide, msg.data.filepath);
if (fullPath) {
this.ide.openFile(fullPath);
}
this.ide.openFile(msg.data.filepath);
});
this.onWebview("vscode/openMoveRightMarkdown", (msg) => {
vscode.commands.executeCommand(
"markdown.showPreview",
vscode.Uri.file(
path.join(
getExtensionUri().fsPath,
"media",
"move-chat-panel-right.md",
),
vscode.Uri.joinPath(
getExtensionUri(),
"media",
"move-chat-panel-right.md",
),
);
});
@ -175,25 +169,14 @@ export class VsCodeMessenger {
fileContent: data.text,
});
let filepath = data.filepath;
// If there is a filepath, verify it exists and then open the file
if (filepath) {
const fullPath = getFullyQualifiedPath(ide, filepath);
if (!fullPath) {
return;
}
const fileExists = await this.ide.fileExists(fullPath);
// If there is no existing file at the path, create it
if (data.filepath) {
const fileExists = await this.ide.fileExists(data.filepath);
if (!fileExists) {
await this.ide.writeFile(fullPath, "");
await this.ide.openFile(fullPath);
await this.ide.writeFile(data.filepath, "");
await this.ide.openFile(data.filepath);
}
await this.ide.openFile(fullPath);
await this.ide.openFile(data.filepath);
}
// Get active text editor
@ -282,25 +265,7 @@ export class VsCodeMessenger {
});
this.onWebview("showTutorial", async (msg) => {
const tutorialPath = path.join(
getExtensionUri().fsPath,
"continue_tutorial.py",
);
// Ensure keyboard shortcuts match OS
if (process.platform !== "darwin") {
let tutorialContent = fs.readFileSync(tutorialPath, "utf8");
tutorialContent = tutorialContent
.replace("⌘", "^")
.replace("Cmd", "Ctrl");
fs.writeFileSync(tutorialPath, tutorialContent);
}
const doc = await vscode.workspace.openTextDocument(
vscode.Uri.file(tutorialPath),
);
await vscode.window.showTextDocument(doc, {
preview: false,
});
await showTutorial(this.ide);
});
this.onWebview("openUrl", (msg) => {
@ -466,9 +431,6 @@ export class VsCodeMessenger {
this.onWebviewOrCore("showVirtualFile", async (msg) => {
return ide.showVirtualFile(msg.data.name, msg.data.content);
});
this.onWebviewOrCore("getContinueDir", async (msg) => {
return ide.getContinueDir();
});
this.onWebviewOrCore("openFile", async (msg) => {
return ide.openFile(msg.data.path);
});

View file

@ -2,8 +2,9 @@ import path from "path";
import * as vscode from "vscode";
import { DiffManager, DIFF_DIRECTORY } from "../../../diff/horizontal";
import { DiffManager } from "../../../diff/horizontal";
import { getMetaKeyLabel } from "../../../util/util";
import { getDiffsDirectoryPath } from "core/util/paths";
export class DiffViewerCodeLensProvider implements vscode.CodeLensProvider {
constructor(private diffManager: DiffManager) {}
@ -12,7 +13,7 @@ export class DiffViewerCodeLensProvider implements vscode.CodeLensProvider {
document: vscode.TextDocument,
_: vscode.CancellationToken,
): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
if (path.dirname(document.uri.fsPath) === DIFF_DIRECTORY) {
if (path.dirname(document.uri.fsPath) === getDiffsDirectoryPath()) {
const codeLenses: vscode.CodeLens[] = [];
let range = new vscode.Range(0, 0, 1, 0);
const diffInfo = this.diffManager.diffAtNewFilepath(

View file

@ -7,11 +7,7 @@ import {
CONTINUE_WORKSPACE_KEY,
getContinueWorkspaceConfig,
} from "../../../util/workspaceConfig";
const TUTORIAL_FILE_NAME = "continue_tutorial.py";
function isTutorialFile(uri: vscode.Uri) {
return uri.fsPath.endsWith(TUTORIAL_FILE_NAME);
}
import { isTutorialFile } from "../../../util/tutorial";
export const ENABLE_QUICK_ACTIONS_KEY = "enableQuickActions";

View file

@ -248,7 +248,7 @@ export class QuickEdit {
private setActiveEditorAndPrevInput(editor: vscode.TextEditor) {
const existingHandler = this.verticalDiffManager.getHandlerForFile(
editor.document.uri.fsPath ?? "",
editor.document.uri.toString(),
);
this.editorWhenOpened = editor;
@ -447,8 +447,8 @@ export class QuickEdit {
if (searchResults.length > 0) {
quickPick.items = searchResults
.map(({ filename }) => ({
label: filename,
.map(({ relativePath }) => ({
label: relativePath,
alwaysShow: true,
}))
.slice(0, QuickEdit.maxFileSearchResults);

View file

@ -0,0 +1,27 @@
import { IDE } from "core";
import { getExtensionUri } from "./vscode";
import * as vscode from "vscode";
const TUTORIAL_FILE_NAME = "continue_tutorial.py";
export function getTutorialUri(): vscode.Uri {
return vscode.Uri.joinPath(getExtensionUri(), TUTORIAL_FILE_NAME);
}
export function isTutorialFile(uri: vscode.Uri) {
return uri.path.endsWith(TUTORIAL_FILE_NAME);
}
export async function showTutorial(ide: IDE) {
const tutorialUri = getTutorialUri();
// Ensure keyboard shortcuts match OS
if (process.platform !== "darwin") {
let tutorialContent = await ide.readFile(tutorialUri.toString());
tutorialContent = tutorialContent.replace("⌘", "^").replace("Cmd", "Ctrl");
await ide.writeFile(tutorialUri.toString(), tutorialContent);
}
const doc = await vscode.workspace.openTextDocument(tutorialUri);
await vscode.window.showTextDocument(doc, {
preview: false,
});
}

View file

@ -1,6 +1,3 @@
import fs from "node:fs";
import path from "path";
import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol";
import { WebviewMessengerResult } from "core/protocol/util";
import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo";
@ -12,25 +9,6 @@ import * as vscode from "vscode";
import { IMessenger } from "../../../core/protocol/messenger";
import { showFreeTrialLoginMessage } from "./util/messages";
import { getExtensionUri } from "./util/vscode";
export async function showTutorial() {
const tutorialPath = path.join(
getExtensionUri().fsPath,
"continue_tutorial.py",
);
// Ensure keyboard shortcuts match OS
if (process.platform !== "darwin") {
let tutorialContent = fs.readFileSync(tutorialPath, "utf8");
tutorialContent = tutorialContent.replace("⌘", "^").replace("Cmd", "Ctrl");
fs.writeFileSync(tutorialPath, tutorialContent);
}
const doc = await vscode.workspace.openTextDocument(
vscode.Uri.file(tutorialPath),
);
await vscode.window.showTextDocument(doc, { preview: false });
}
export class VsCodeWebviewProtocol
implements IMessenger<FromWebviewProtocol, ToWebviewProtocol>

View file

@ -4,12 +4,13 @@ import {
ChevronRightIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { useState } from "react";
import { useMemo, useState } from "react";
import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview";
import { getMarkdownLanguageTagForFile } from "core/util";
import styled from "styled-components";
import { CodeToEdit } from "core";
import { getLastNPathParts } from "core/util/uri";
import { rifWithContentsToContextItem } from "core/commands/util";
import { getUriPathBasename } from "core/util/uri";
export interface CodeToEditListItemProps {
code: CodeToEdit;
@ -36,7 +37,15 @@ export default function CodeToEditListItem({
}: CodeToEditListItemProps) {
const [showCodeSnippet, setShowCodeSnippet] = useState(false);
const filepath = code.filepath.split("/").pop() || code.filepath;
const context = useMemo(() => {
return rifWithContentsToContextItem({
contents: code.contents,
range: {
start: {},
},
});
}, []);
const basename = getUriPathBasename(code.filepath);
const fileSubpath = getLastNPathParts(code.filepath, 2);
let isInsertion = false;

View file

@ -29,10 +29,14 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) {
const isUrl = contextItem.uri?.type === "url";
function openContextItem() {
const { uri, name, description, content } = contextItem;
const { uri, name, content } = contextItem;
if (isUrl) {
ideMessenger.post("openUrl", uri.value);
if (uri?.value) {
ideMessenger.post("openUrl", uri.value);
} else {
console.error("Couldn't open url", uri);
}
} else if (uri) {
const isRangeInFile = name.includes(" (") && name.endsWith(")");
@ -44,7 +48,7 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) {
rif.range.end.line,
);
} else {
ideMessenger.ide.openFile(description);
ideMessenger.ide.openFile(uri.value);
}
} else {
ideMessenger.ide.showVirtualFile(name, content);

View file

@ -5,7 +5,7 @@ import {
} from "@heroicons/react/24/outline";
import { ContextItemWithId } from "core";
import { dedent, getMarkdownLanguageTagForFile } from "core/util";
import React, { useContext } from "react";
import React, { useContext, useMemo } from "react";
import styled from "styled-components";
import { defaultBorderRadius, lightGray, vscEditorBackground } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
@ -13,6 +13,7 @@ import { getFontSize } from "../../util";
import FileIcon from "../FileIcon";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import StyledMarkdownPreview from "./StyledMarkdownPreview";
import { ctxItemToRifWithContents } from "core/commands/util";
const PreviewMarkdownDiv = styled.div<{
borderColor?: string;
@ -49,7 +50,6 @@ interface CodeSnippetPreviewProps {
const MAX_PREVIEW_HEIGHT = 300;
// Pre-compile the regular expression outside of the function
const backticksRegex = /`{3,}/gm;
function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
@ -58,12 +58,14 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
const [collapsed, setCollapsed] = React.useState(true);
const [hovered, setHovered] = React.useState(false);
const content = dedent`${props.item.content}`;
const content = useMemo(() => {
return dedent`${props.item.content}`;
}, [props.item.content]);
const fence = React.useMemo(() => {
const fence = useMemo(() => {
const backticks = content.match(backticksRegex);
return backticks ? backticks.sort().at(-1) + "`" : "```";
}, [props.item.content]);
}, [content]);
const codeBlockRef = React.useRef<HTMLDivElement>(null);
@ -79,19 +81,19 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
<PreviewMarkdownHeader
className="flex cursor-pointer justify-between"
onClick={() => {
if (props.item.id.providerTitle === "file") {
if (
props.item.id.providerTitle === "file" &&
props.item.uri?.value
) {
ideMessenger.post("showFile", {
filepath: props.item.description,
filepath: props.item.uri.value,
});
} else if (props.item.id.providerTitle === "code") {
const lines = props.item.name
.split("(")[1]
.split(")")[0]
.split("-");
const rif = ctxItemToRifWithContents(props.item);
ideMessenger.ide.showLines(
props.item.description.split(" ")[0],
parseInt(lines[0]) - 1,
parseInt(lines[1]) - 1,
rif.filepath,
rif.range.start.line,
rif.range.end.line,
);
} else {
ideMessenger.post("showVirtualFile", {
@ -124,9 +126,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
ref={codeBlockRef}
>
<StyledMarkdownPreview
source={`${fence}${getMarkdownLanguageTagForFile(
props.item.description.split(" ")[0],
)} ${props.item.description}\n${content}\n${fence}`}
source={`${fence}${getMarkdownLanguageTagForFile(props.item.name)} ${props.item.description}\n${content}\n${fence}`}
/>
</div>