🚧 update references automatically

This commit is contained in:
Nate Sesti 2023-11-04 18:59:07 -07:00
parent 4eee6e380f
commit 4763da10c9
12 changed files with 620 additions and 1517 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -129,6 +129,11 @@
"command": "continue.selectFilesAsContext",
"category": "Continue",
"title": "Continue: Select Files as Context"
},
{
"command": "continue.updateAllReferences",
"category": "Continue",
"title": "Update All References"
}
],
"keybindings": [
@ -195,8 +200,7 @@
"editor/context": [
{
"submenu": "continue.continueSubMenu",
"group": "1_debug@1",
"when": "editorHasSelection"
"group": "1_debug@1"
}
],
"continue.continueSubMenu": [
@ -209,6 +213,10 @@
"command": "continue.focusContinueInputWithEdit",
"group": "Continue",
"when": "editorHasSelection"
},
{
"command": "continue.updateAllReferences",
"group": "Continue"
}
],
"explorer/context": [

View file

@ -207,6 +207,17 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
addEntireFileToContext(uri, false);
}
},
"continue.updateAllReferences": (filepath: vscode.Uri) => {
// Get the cursor position in the editor
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const position = editor.selection.active;
ideProtocolClient.sendMainUserInput(
`/references ${filepath.fsPath} ${position.line} ${position.character}`
);
},
};
export function registerAllCommands(context: vscode.ExtensionContext) {

View file

@ -22,7 +22,7 @@ const path = require("path");
import { v4 } from "uuid";
import { windowId } from "./activation/activate";
import * as io from "socket.io-client";
import { debugPanelWebview } from "./debugPanel";
import { debugPanelWebview, getSidebarContent } from "./debugPanel";
const continueVirtualDocumentScheme = "continue";
@ -206,7 +206,7 @@ class IdeProtocolClient {
messageId: string,
callback: (data: any) => void
) {
const respond = (messageType: string, responseData: any) => {
const respond = (responseData: any) => {
callback({
message_type: messageType,
data: responseData,
@ -215,54 +215,54 @@ class IdeProtocolClient {
};
switch (messageType) {
case "highlightedCode":
respond("highlightedCode", {
respond({
highlightedCode: this.getHighlightedCode(),
});
break;
case "workspaceDirectory":
respond("workspaceDirectory", {
respond({
workspaceDirectory: this.getWorkspaceDirectory(),
});
break;
case "uniqueId":
respond("uniqueId", {
respond({
uniqueId: this.getUniqueId(),
});
break;
case "ide":
respond("ide", {
respond({
name: "vscode",
version: vscode.version,
remoteName: vscode.env.remoteName,
});
break;
case "fileExists":
respond("fileExists", {
respond({
exists: await this.fileExists(data.filepath),
});
break;
case "getUserSecret":
respond("getUserSecret", {
respond({
value: await this.getUserSecret(data.key),
});
break;
case "openFiles":
respond("openFiles", {
respond({
openFiles: this.getOpenFiles(),
});
break;
case "visibleFiles":
respond("visibleFiles", {
respond({
visibleFiles: this.getVisibleFiles(),
});
break;
case "readFile":
respond("readFile", {
respond({
contents: await this.readFile(data.filepath),
});
break;
case "getTerminalContents":
respond("getTerminalContents", {
respond({
contents: await this.getTerminalContents(data.commands),
});
break;
@ -277,13 +277,13 @@ class IdeProtocolClient {
console.log("Error listing directory contents: ", e);
contents = [];
}
respond("listDirectoryContents", {
respond({
contents,
});
break;
case "editFile":
const fileEdit = await this.editFile(data.edit);
respond("editFile", {
respond({
fileEdit,
});
break;
@ -291,7 +291,7 @@ class IdeProtocolClient {
this.highlightCode(data.rangeInFile, data.color);
break;
case "runCommand":
respond("runCommand", {
respond({
output: await this.runCommand(data.command),
});
break;
@ -328,14 +328,73 @@ class IdeProtocolClient {
case "showDiff":
await this.showDiff(data.filepath, data.replacement, data.step_index);
break;
case "showMultiFileEdit":
this.showMultiFileEdit(data.edits);
break;
case "getSessionId":
case "connected":
break;
case "textDocument/definition":
respond({
locations: await this.gotoDefinition(data.filepath, data.position),
});
break;
case "textDocument/documentSymbol":
respond({ symbols: await this.documentSymbol(data.filepath) });
break;
case "textDocument/references":
const locations = await this.references(data.filepath, data.position);
respond({
locations,
});
break;
case "textDocument/foldingRange":
respond({
ranges: await this.foldingRanges(data.filepath),
});
break;
default:
throw Error("Unknown message type:" + messageType);
}
}
async gotoDefinition(
filepath: string,
position: vscode.Position
): Promise<vscode.Location[]> {
const locations: vscode.Location[] = await vscode.commands.executeCommand(
"vscode.executeDefinitionProvider",
uriFromFilePath(filepath),
position
);
return locations;
}
async documentSymbol(filepath: string): Promise<vscode.DocumentSymbol[]> {
return await vscode.commands.executeCommand(
"vscode.executeDocumentSymbolProvider",
uriFromFilePath(filepath)
);
}
async references(
filepath: string,
position: vscode.Position
): Promise<vscode.Location[]> {
return await vscode.commands.executeCommand(
"vscode.executeReferenceProvider",
uriFromFilePath(filepath),
position
);
}
async foldingRanges(filepath: string): Promise<vscode.FoldingRange[]> {
return await vscode.commands.executeCommand(
"vscode.executeFoldingRangeProvider",
uriFromFilePath(filepath)
);
}
getWorkspaceDirectory() {
if (!vscode.workspace.workspaceFolders) {
// Return the home directory
@ -414,6 +473,16 @@ class IdeProtocolClient {
await diffManager.writeDiff(filepath, replacement, step_index);
}
showMultiFileEdit(edits: FileEdit[]) {
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
const panel = vscode.window.createWebviewPanel(
"continue.continueGUIView",
"Continue",
vscode.ViewColumn.One
);
panel.webview.html = getSidebarContent(panel, "/monaco", edits);
}
openFile(filepath: string) {
// vscode has a builtin open/get open files
openEditorAndRevealRange(filepath, undefined, vscode.ViewColumn.One);

View file

@ -4,13 +4,15 @@ import { getExtensionUri, getNonce, getUniqueId } from "./util/vscode";
import { setFocusedOnContinueInput } from "./commands";
import { ideProtocolClient, windowId } from "./activation/activate";
import * as io from "socket.io-client";
import { FileEdit } from "../schema/FileEdit";
let sockets: { [url: string]: io.Socket | undefined } = {};
export let debugPanelWebview: vscode.Webview | undefined;
export function getSidebarContent(
panel: vscode.WebviewPanel | vscode.WebviewView,
page: string | undefined = undefined
page: string | undefined = undefined,
edits: FileEdit[] | undefined = undefined
): string {
debugPanelWebview = panel.webview;
panel.onDidDispose(() => {
@ -253,6 +255,9 @@ export function getSidebarContent(
(folder) => folder.uri.fsPath
) || []
)}</script>
${edits && `<script>window.edits = ${JSON.stringify(edits)}</script>`}
${page && `<script>window.location.pathname = "${page}"</script>`}
</body>
</html>`;
}

View file

@ -1,5 +1,9 @@
from typing import Type, Union
from ...models.main import Position, PositionInFile
from ..steps.refactor import RefactorReferencesStep
from ..steps.clear_history import ClearHistoryStep
from ..steps.comment_code import CommentCodeStep
from ..steps.share_session import ShareSessionStep
@ -103,4 +107,14 @@ class DefaultPolicy(Policy):
if user_input.startswith("/codebase "):
return AnswerQuestionChroma(user_input=user_input[len("/codebase ") :])
if user_input.startswith("/references "):
args = user_input.split()
return RefactorReferencesStep(
user_input="Update this reference to reflect the new definition",
symbol_location=PositionInFile(
filepath=args[1],
position=Position(line=int(args[2]), character=int(args[3])),
),
)
return self.default_step(**self.default_params)

View file

@ -3,7 +3,7 @@ from typing import List, Optional
from ripgrepy import Ripgrepy
from ...core.main import Step
from ...core.main import SetStep, Step
from ...core.models import Models
from ...core.sdk import ContinueSDK
from ...libs.llm.prompts.edit import codellama_edit_prompt
@ -24,11 +24,8 @@ class RefactorReferencesStep(Step):
return f"Renamed all instances of `{self.function_name}` to `{self.new_function_name}` in `{self.filepath}`"
async def run(self, sdk: ContinueSDK):
while sdk.lsp is None or not sdk.lsp.ready:
await asyncio.sleep(0.1)
references = await sdk.lsp.find_references(
self.symbol_location.position, self.symbol_location.filepath, False
references = await sdk.ide.find_references(
self.symbol_location.filepath, self.symbol_location.position, False
)
await sdk.run_step(
ParallelEditStep(user_input=self.user_input, range_in_files=references)
@ -69,9 +66,11 @@ class ParallelEditStep(Step):
hide: bool = True
async def single_edit(self, sdk: ContinueSDK, range_in_file: RangeInFile):
async def single_edit(
self, sdk: ContinueSDK, range_in_file: RangeInFile
) -> FileEdit:
# TODO: Can use folding info to get a more intuitively shaped range
expanded_range = await sdk.lsp.get_enclosing_folding_range(range_in_file)
expanded_range = await sdk.ide.get_enclosing_folding_range(range_in_file)
if (
expanded_range is None
or expanded_range.range.start.line != range_in_file.range.start.line
@ -109,15 +108,13 @@ class ParallelEditStep(Step):
print(new_code + "\n\n-------------------\n\n")
await sdk.ide.applyFileSystemEdit(
FileEdit(
filepath=range_in_file.filepath,
range=expanded_range,
replacement=new_code,
)
return FileEdit(
filepath=range_in_file.filepath,
range=expanded_range,
replacement=new_code,
)
async def edit_file(self, sdk: ContinueSDK, filepath: str):
async def edit_file(self, sdk: ContinueSDK, filepath: str) -> List[FileEdit]:
ranges_in_file = [
range_in_file
for range_in_file in self.range_in_files
@ -125,12 +122,24 @@ class ParallelEditStep(Step):
]
# Sort in reverse order so that we don't mess up the ranges
ranges_in_file.sort(key=lambda x: x.range.start.line, reverse=True)
for i in range(len(ranges_in_file)):
await self.single_edit(sdk=sdk, range_in_file=ranges_in_file[i])
return await asyncio.gather(
*[
self.single_edit(
sdk=sdk,
range_in_file=ranges_in_file[i],
)
for i in range(len(ranges_in_file))
]
)
async def run(self, sdk: ContinueSDK):
tasks = []
for filepath in set([rif.filepath for rif in self.range_in_files]):
tasks.append(self.edit_file(sdk=sdk, filepath=filepath))
await asyncio.gather(*tasks)
edits_per_file = await asyncio.gather(*tasks)
all_edits = []
for edits in edits_per_file:
all_edits += edits
await sdk.ide.showMultiFileEdit(edits=all_edits)

View file

@ -10,7 +10,7 @@ from typing import (
List,
Optional,
)
from ...models.main import Position
from ...libs.util.create_async_task import create_async_task
from ...models.filesystem import (
FileSystem,
@ -107,6 +107,22 @@ class FileExistsResponse(BaseModel):
exists: bool
class GotoDefinitionResponse(BaseModel):
locations: List[Dict[str, Any]]
class ReferencesResponse(BaseModel):
locations: List[Dict[str, Any]]
class DocumentSymbolResponse(BaseModel):
symbols: List[Dict[str, Any]]
class FoldingRangeResponse(BaseModel):
ranges: List[Dict[str, Any]]
# endregion
@ -214,6 +230,11 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
},
)
async def showMultiFileEdit(self, edits: List[FileEdit]):
await self.messenger.send(
"showMultiFileEdit", {"edits": [edit.dict() for edit in edits]}
)
async def setFileOpen(self, filepath: str, open: bool = True):
# Autopilot needs access to this.
await self.messenger.send("setFileOpen", {"filepath": filepath, "open": open})
@ -472,3 +493,53 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
raise TypeError("Unknown FileSystemEdit type: " + str(type(edit)))
return EditDiff(forward=edit, backward=backward)
# region Language Server Protocol
async def goto_definition(self, filepath: str, position: Position):
return await self.messenger.send_and_receive(
{"filepath": filepath, "position": position.dict()},
GotoDefinitionResponse,
"textDocument/definition",
)
async def document_symbol(self, filepath: str):
return await self.messenger.send_and_receive(
"textDocument/documentSymbol",
DocumentSymbolResponse,
textDocument={"uri": filepath},
)
async def find_references(
self, filepath: str, position: Position, include_declaration: bool = False
):
return await self.messenger.send_and_receive(
{
"filepath": filepath,
"position": position.dict(),
"context": {"includeDeclaration": include_declaration},
},
ReferencesResponse,
"textDocument/references",
)
async def folding_range(self, filepath: str):
return await self.messenger.send_and_receive(
{"filepath": filepath},
FoldingRangeResponse,
"textDocument/foldingRange",
)
async def get_enclosing_folding_range(self, rif: RangeInFile):
ranges = await self.folding_range(rif.filepath)
max_start_position = Position(line=0, character=0)
max_range = None
for r in ranges:
if r.range.contains(rif.range.start):
if r.range.start > max_start_position:
max_start_position = r.range.start
max_range = r
return max_range
# endregion

View file

@ -1,6 +1,8 @@
from abc import ABC, abstractmethod
from typing import Callable, Dict, List, Optional, Union
from ...models.main import Position
from ...models.websockets import WebsocketsMessage
from fastapi import WebSocket
@ -150,3 +152,29 @@ class AbstractIdeProtocolServer(ABC):
workspace_directory: str
unique_id: str
# region Language Server Protocol
@abstractmethod
async def goto_definition(self, filepath: str, position: Position):
raise NotImplementedError()
@abstractmethod
async def document_symbol(self, filepath: str):
raise NotImplementedError()
@abstractmethod
async def find_references(
self, filepath: str, position: Position, include_declaration: bool = False
):
raise NotImplementedError()
@abstractmethod
async def folding_range(self, filepath: str):
raise NotImplementedError()
@abstractmethod
async def get_enclosing_folding_range(self, position: Position, filepath: str):
raise NotImplementedError()
# endregion