(BROKEN) path -> uri vscode utils continued

This commit is contained in:
Dallin Romney 2024-12-10 20:09:07 -08:00
parent 2dfd8d2048
commit 2225d0d702
8 changed files with 101 additions and 95 deletions

View file

@ -72,12 +72,12 @@ const SEP_REGEX = /[\\/]/;
// return filepath.split(SEP_REGEX).pop() ?? "";
// }
// export function getLastNPathParts(filepath: string, n: number): string {
// if (n <= 0) {
// return "";
// }
// return filepath.split(SEP_REGEX).slice(-n).join("/");
// }
export function getLastNPathParts(filepath: string, n: number): string {
if (n <= 0) {
return "";
}
return filepath.split(SEP_REGEX).slice(-n).join("/");
}
// export function groupByLastNPathParts(
// filepaths: string[],

View file

@ -349,7 +349,7 @@ class VsCodeIde implements IDE {
filename === ".continuerc.json"
) {
const contents = await this.readFile(
vscode.Uri.joinPath(workspaceDir, filename).fsPath,
vscode.Uri.joinPath(workspaceDir, filename).toString(),
);
configs.push(JSON.parse(contents));
}
@ -509,7 +509,7 @@ class VsCodeIde implements IDE {
return tabArray
.filter((t) => t.isPinned)
.map((t) => (t.input as vscode.TabInputText).uri.fsPath);
.map((t) => (t.input as vscode.TabInputText).uri.toString());
}
private async _searchDir(query: string, dir: string): Promise<string> {
@ -572,7 +572,7 @@ class VsCodeIde implements IDE {
}
return vscode.languages.getDiagnostics(uri).map((d) => {
return {
filepath: uri.fsPath,
filepath: uri.toString(),
range: {
start: {
line: d.range.start.line,
@ -607,7 +607,7 @@ class VsCodeIde implements IDE {
}
async listDir(dir: string): Promise<[string, FileType][]> {
return vscode.workspace.fs.readDirectory(uriFromFilePath(dir)) as any;
return vscode.workspace.fs.readDirectory(vscode.Uri.parse(dir)) as any;
}
getIdeSettingsSync(): IdeSettings {

View file

@ -10,16 +10,16 @@ import { getMetaKeyLabel, getPlatform } from "../util/util";
import type { VsCodeWebviewProtocol } from "../webviewProtocol";
interface DiffInfo {
originalFilepath: string;
newFilepath: string;
originalUri: string;
newUri: string;
editor?: vscode.TextEditor;
step_index: number;
range: vscode.Range;
}
async function readFile(path: string): Promise<string> {
async function readFile(uri: vscode.Uri): Promise<string> {
return await vscode.workspace.fs
.readFile(uriFromFilePath(path))
.readFile(uri)
.then((bytes) => new TextDecoder().decode(bytes));
}

View file

@ -10,6 +10,7 @@ import {
import type { VerticalDiffCodeLens } from "./manager";
import type { ApplyState, DiffLine } from "core";
import URI from "uri-js";
export interface VerticalDiffHandlerOptions {
input?: string;
@ -27,8 +28,8 @@ export class VerticalDiffHandler implements vscode.Disposable {
private newLinesAdded = 0;
private deletionBuffer: string[] = [];
private redDecorationManager: DecorationTypeRangeManager;
private get filepath() {
return this.editor.document.uri.fsPath;
private get fileUri() {
return this.editor.document.uri.toString();
}
public insertedInCurrentBlock = 0;
public get range(): vscode.Range {
@ -45,8 +46,8 @@ export class VerticalDiffHandler implements vscode.Disposable {
string,
VerticalDiffCodeLens[]
>,
private readonly clearForFilepath: (
filepath: string | undefined,
private readonly clearForFileUri: (
fileUri: string | undefined,
accept: boolean,
) => void,
private readonly refreshCodeLens: () => void,
@ -65,8 +66,11 @@ export class VerticalDiffHandler implements vscode.Disposable {
);
const disposable = vscode.window.onDidChangeActiveTextEditor((editor) => {
if (!editor) {
return;
}
// When we switch away and back to this editor, need to re-draw decorations
if (editor?.document.uri.fsPath === this.filepath) {
if (URI.equal(editor.document.uri.toString(), this.fileUri)) {
this.editor = editor;
this.redDecorationManager.applyToNewEditor(editor);
this.greenDecorationManager.applyToNewEditor(editor);
@ -93,7 +97,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
}
if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) {
const blocks = this.editorToVerticalDiffCodeLens.get(this.filepath) || [];
const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) || [];
blocks.push({
start: this.currentLineIndex - this.insertedInCurrentBlock,
@ -101,7 +105,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
numGreen: this.insertedInCurrentBlock,
});
this.editorToVerticalDiffCodeLens.set(this.filepath, blocks);
this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
}
if (this.deletionBuffer.length === 0) {
@ -249,7 +253,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
this.greenDecorationManager.clear();
this.clearIndexLineDecorations();
this.editorToVerticalDiffCodeLens.delete(this.filepath);
this.editorToVerticalDiffCodeLens.delete(this.fileUri);
await this.editor.edit(
(editBuilder) => {
@ -270,7 +274,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
this.options.onStatusUpdate(
"closed",
this.editorToVerticalDiffCodeLens.get(this.filepath)?.length ?? 0,
this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0,
this.editor.document.getText(),
);
@ -362,19 +366,19 @@ export class VerticalDiffHandler implements vscode.Disposable {
this.options.onStatusUpdate(
"done",
this.editorToVerticalDiffCodeLens.get(this.filepath)?.length ?? 0,
this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0,
this.editor.document.getText(),
);
// Reject on user typing
// const listener = vscode.workspace.onDidChangeTextDocument((e) => {
// if (e.document.uri.fsPath === this.filepath) {
// if (URI.equal(e.document.uri.toString(), this.fileUri)) {
// this.clear(false);
// listener.dispose();
// }
// });
} catch (e) {
this.clearForFilepath(this.filepath, false);
this.clearForFileUri(this.fileUri, false);
throw e;
}
return diffLines;
@ -415,7 +419,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
this.shiftCodeLensObjects(startLine, offset);
const numDiffs =
this.editorToVerticalDiffCodeLens.get(this.filepath)?.length ?? 0;
this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0;
const status = numDiffs === 0 ? "closed" : undefined;
this.options.onStatusUpdate(
@ -429,7 +433,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
// Shift the codelens objects
const blocks =
this.editorToVerticalDiffCodeLens
.get(this.filepath)
.get(this.fileUri)
?.filter((x) => x.start !== startLine)
.map((x) => {
if (x.start > startLine) {
@ -437,18 +441,18 @@ export class VerticalDiffHandler implements vscode.Disposable {
}
return x;
}) || [];
this.editorToVerticalDiffCodeLens.set(this.filepath, blocks);
this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
this.refreshCodeLens();
}
public updateLineDelta(
filepath: string,
fileUri: string,
startLine: number,
lineDelta: number,
) {
// Retrieve the diff blocks for the given file
const blocks = this.editorToVerticalDiffCodeLens.get(filepath);
const blocks = this.editorToVerticalDiffCodeLens.get(fileUri);
if (!blocks) {
return;
}
@ -462,7 +466,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
}
public hasDiffForCurrentFile(): boolean {
const diffBlocks = this.editorToVerticalDiffCodeLens.get(this.filepath);
const diffBlocks = this.editorToVerticalDiffCodeLens.get(this.fileUri);
return diffBlocks !== undefined && diffBlocks.length > 0;
}
}

View file

@ -9,6 +9,7 @@ import EditDecorationManager from "../../quickEdit/EditDecorationManager";
import { VsCodeWebviewProtocol } from "../../webviewProtocol";
import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler";
import URI from "uri-js";
export interface VerticalDiffCodeLens {
start: number;
@ -19,9 +20,9 @@ export interface VerticalDiffCodeLens {
export class VerticalDiffManager {
public refreshCodeLens: () => void = () => {};
private filepathToHandler: Map<string, VerticalDiffHandler> = new Map();
private fileUriToHandler: Map<string, VerticalDiffHandler> = new Map();
filepathToCodeLens: Map<string, VerticalDiffCodeLens[]> = new Map();
fileUriToCodeLens: Map<string, VerticalDiffCodeLens[]> = new Map();
private userChangeListener: vscode.Disposable | undefined;
@ -36,35 +37,35 @@ export class VerticalDiffManager {
}
createVerticalDiffHandler(
filepath: string,
fileUri: string,
startLine: number,
endLine: number,
options: VerticalDiffHandlerOptions,
) {
if (this.filepathToHandler.has(filepath)) {
this.filepathToHandler.get(filepath)?.clear(false);
this.filepathToHandler.delete(filepath);
if (this.fileUriToHandler.has(fileUri)) {
this.fileUriToHandler.get(fileUri)?.clear(false);
this.fileUriToHandler.delete(fileUri);
}
const editor = vscode.window.activeTextEditor; // TODO
if (editor && editor.document.uri.fsPath === filepath) {
if (editor && URI.equal(editor.document.uri.toString(), fileUri)) {
const handler = new VerticalDiffHandler(
startLine,
endLine,
editor,
this.filepathToCodeLens,
this.clearForFilepath.bind(this),
this.fileUriToCodeLens,
this.clearForfileUri.bind(this),
this.refreshCodeLens,
options,
);
this.filepathToHandler.set(filepath, handler);
this.fileUriToHandler.set(fileUri, handler);
return handler;
} else {
return undefined;
}
}
getHandlerForFile(filepath: string) {
return this.filepathToHandler.get(filepath);
getHandlerForFile(fileUri: string) {
return this.fileUriToHandler.get(fileUri);
}
// Creates a listener for document changes by user.
@ -77,8 +78,8 @@ export class VerticalDiffManager {
this.userChangeListener = vscode.workspace.onDidChangeTextDocument(
(event) => {
// Check if there is an active handler for the affected file
const filepath = event.document.uri.fsPath;
const handler = this.getHandlerForFile(filepath);
const fileUri = event.document.uri.toString();
const handler = this.getHandlerForFile(fileUri);
if (handler) {
// If there is an active diff for that file, handle the document change
this.handleDocumentChange(event, handler);
@ -108,26 +109,26 @@ export class VerticalDiffManager {
// Update the diff handler with the new line delta
handler.updateLineDelta(
event.document.uri.fsPath,
event.document.uri.toString(),
change.range.start.line,
lineDelta,
);
});
}
clearForFilepath(filepath: string | undefined, accept: boolean) {
if (!filepath) {
clearForfileUri(fileUri: string | undefined, accept: boolean) {
if (!fileUri) {
const activeEditor = vscode.window.activeTextEditor;
if (!activeEditor) {
return;
}
filepath = activeEditor.document.uri.fsPath;
fileUri = activeEditor.document.uri.toString();
}
const handler = this.filepathToHandler.get(filepath);
const handler = this.fileUriToHandler.get(fileUri);
if (handler) {
handler.clear(accept);
this.filepathToHandler.delete(filepath);
this.fileUriToHandler.delete(fileUri);
}
this.disableDocumentChangeListener();
@ -137,28 +138,28 @@ export class VerticalDiffManager {
async acceptRejectVerticalDiffBlock(
accept: boolean,
filepath?: string,
fileUri?: string,
index?: number,
) {
if (!filepath) {
if (!fileUri) {
const activeEditor = vscode.window.activeTextEditor;
if (!activeEditor) {
return;
}
filepath = activeEditor.document.uri.fsPath;
fileUri = activeEditor.document.uri.toString();
}
if (typeof index === "undefined") {
index = 0;
}
const blocks = this.filepathToCodeLens.get(filepath);
const blocks = this.fileUriToCodeLens.get(fileUri);
const block = blocks?.[index];
if (!blocks || !block) {
return;
}
const handler = this.getHandlerForFile(filepath);
const handler = this.getHandlerForFile(fileUri);
if (!handler) {
return;
}
@ -175,7 +176,7 @@ export class VerticalDiffManager {
);
if (blocks.length === 1) {
this.clearForFilepath(filepath, true);
this.clearForfileUri(fileUri, true);
} else {
// Re-enable listener for user changes to file
this.enableDocumentChangeListener();
@ -191,17 +192,17 @@ export class VerticalDiffManager {
) {
vscode.commands.executeCommand("setContext", "continue.diffVisible", true);
// Get the current editor filepath/range
// Get the current editor fileUri/range
let editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const filepath = editor.document.uri.fsPath;
const fileUri = editor.document.uri.toString();
const startLine = 0;
const endLine = editor.document.lineCount - 1;
// Check for existing handlers in the same file the new one will be created in
const existingHandler = this.getHandlerForFile(filepath);
const existingHandler = this.getHandlerForFile(fileUri);
if (existingHandler) {
existingHandler.clear(false);
}
@ -212,7 +213,7 @@ export class VerticalDiffManager {
// Create new handler with determined start/end
const diffHandler = this.createVerticalDiffHandler(
filepath,
fileUri,
startLine,
endLine,
{
@ -223,7 +224,7 @@ export class VerticalDiffManager {
status,
numDiffs,
fileContent,
filepath,
filepath: fileUri,
}),
},
);
@ -280,7 +281,7 @@ export class VerticalDiffManager {
return undefined;
}
const filepath = editor.document.uri.fsPath;
const fileUri = editor.document.uri.toString();
let startLine, endLine: number;
@ -293,7 +294,7 @@ export class VerticalDiffManager {
}
// Check for existing handlers in the same file the new one will be created in
const existingHandler = this.getHandlerForFile(filepath);
const existingHandler = this.getHandlerForFile(fileUri);
if (existingHandler) {
if (quickEdit) {
@ -333,7 +334,7 @@ export class VerticalDiffManager {
// Create new handler with determined start/end
const diffHandler = this.createVerticalDiffHandler(
filepath,
fileUri,
startLine,
endLine,
{
@ -345,7 +346,7 @@ export class VerticalDiffManager {
status,
numDiffs,
fileContent,
filepath,
filepath: fileUri,
}),
},
);
@ -411,7 +412,7 @@ export class VerticalDiffManager {
suffix,
llm,
input,
getMarkdownLanguageTagForFile(filepath),
getMarkdownLanguageTagForFile(fileUri),
onlyOneInsertion,
);

View file

@ -1,8 +1,9 @@
import { IDE } from "core";
import { getBasename, getLastNPathParts } from "core/util";
import vscode from "vscode";
import { FileSearch } from "../util/FileSearch";
import { getUriPathBasename } from "core/util/uri";
import { getLastNPathParts } from "core/util";
class PromptFilesCompletionItemProvider
implements vscode.CompletionItemProvider
@ -30,13 +31,16 @@ class PromptFilesCompletionItemProvider
}
const searchText = linePrefix.split("@").pop() || "";
const files = this.fileSearch.search(searchText).map(({ filename }) => {
return filename;
});
const files = this.fileSearch.search(searchText);
if (files.length === 0) {
const openFiles = await this.ide.getOpenFiles();
files.push(...openFiles);
files.push(
...openFiles.map((fileUri) => ({
id: fileUri,
relativePath: vscode.workspace.asRelativePath(fileUri),
})),
);
}
// Provide completion items
@ -84,17 +88,10 @@ class PromptFilesCompletionItemProvider
kind: vscode.CompletionItemKind.Field,
},
...files.map((file) => {
const workspaceFolder = vscode.workspace.getWorkspaceFolder(
vscode.Uri.file(file),
);
const relativePath = workspaceFolder
? vscode.workspace.asRelativePath(file)
: file;
return {
label: getBasename(file),
detail: getLastNPathParts(file, 2),
insertText: relativePath,
label: getUriPathBasename(file.id),
detail: getLastNPathParts(file.relativePath, 2),
insertText: file.relativePath,
kind: vscode.CompletionItemKind.File,
};
}),

View file

@ -4,19 +4,23 @@ import { walkDir } from "core/indexing/walkDir";
import MiniSearch from "minisearch";
import * as vscode from "vscode";
type FileMiniSearchResult = { filename: string };
type FileMiniSearchResult = { relativePath: string; id: string };
/*
id = file URI
*/
export class FileSearch {
constructor(private readonly ide: IDE) {
this.initializeFileSearchState();
}
private miniSearch = new MiniSearch<FileMiniSearchResult>({
fields: ["filename"],
storeFields: ["filename"],
fields: ["relativePath", "id"],
storeFields: ["relativePath", "id"],
searchOptions: {
prefix: true,
fuzzy: 2,
fields: ["relativePath"],
},
});
private async initializeFileSearchState() {
@ -28,12 +32,12 @@ export class FileSearch {
}),
);
const filenames = results.flat().map((file) => ({
id: file,
filename: vscode.workspace.asRelativePath(file),
}));
this.miniSearch.addAll(filenames);
this.miniSearch.addAll(
results.flat().map((file) => ({
id: file,
relativePath: vscode.workspace.asRelativePath(file),
})),
);
}
public search(query: string): FileMiniSearchResult[] {

View file

@ -14,7 +14,7 @@ import {
import { getUniqueId, openEditorAndRevealRange } from "./vscode";
import type { FileEdit, Range, RangeInFile, Thread } from "core";
import type { Range, RangeInFile, Thread } from "core";
import { isUriWithinDirectory } from "core/util/uri";
const util = require("node:util");
@ -217,11 +217,11 @@ export class VsCodeIdeUtils {
.filter((uri) => this.documentIsCode(uri)); // Filter out undesired documents
}
getVisibleFiles(): string[] {
getVisibleFiles(): vscode.Uri[] {
return vscode.window.visibleTextEditors
.filter((editor) => this.documentIsCode(editor.document.uri))
.map((editor) => {
return editor.document.uri.fsPath;
return editor.document.uri;
});
}