From 84c9852167ac26e5d395ebfcc3d199102bfe04f7 Mon Sep 17 00:00:00 2001 From: "bobo.yang" Date: Mon, 8 May 2023 14:03:29 +0800 Subject: [PATCH] apply code to specified file --- src/handler/codeFileApply.ts | 37 ++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/src/handler/codeFileApply.ts b/src/handler/codeFileApply.ts index 2c13188..20016ae 100644 --- a/src/handler/codeFileApply.ts +++ b/src/handler/codeFileApply.ts @@ -1,7 +1,40 @@ import * as vscode from 'vscode'; -export async function applyCodeFile(text: string) { +async function replaceFileContent(uri: vscode.Uri, newContent: string) { + try { + // 创建一个 WorkspaceEdit 对象 + const workspaceEdit = new vscode.WorkspaceEdit(); + + // 获取文件的当前内容 + const document = await vscode.workspace.openTextDocument(uri); + + // 计算文件的完整范围(从文件开始到文件结束) + const fullRange = new vscode.Range( + document.positionAt(0), + document.positionAt(document.getText().length) + ); + + // 使用 WorkspaceEdit 的 replace 方法替换文件的完整范围内容 + workspaceEdit.replace(uri, fullRange, newContent); + + // 应用编辑更改 + await vscode.workspace.applyEdit(workspaceEdit); + + // 显示成功消息 + vscode.window.showInformationMessage('File content replaced successfully.'); + } catch (error) { + // 显示错误消息 + vscode.window.showErrorMessage('Failed to replace file content: ' + error); + } +} + +export async function applyCodeFile(text: string, fileName: string): Promise { + if (fileName) { + await replaceFileContent(vscode.Uri.file(fileName), text); + return; + } + const validVisibleTextEditors = vscode.window.visibleTextEditors.filter(editor => editor.viewColumn !== undefined); if (validVisibleTextEditors.length > 1) { @@ -26,7 +59,7 @@ export async function applyCodeFile(text: string) { } export async function codeFileApply(message: any, panel: vscode.WebviewPanel): Promise { - await applyCodeFile(message.content); + await applyCodeFile(message.content, message.fileName); return; }