apply code to specified file

This commit is contained in:
bobo.yang 2023-05-08 14:03:29 +08:00
parent 8ac8c72ac3
commit 84c9852167

View File

@ -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<void> {
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<void> {
await applyCodeFile(message.content);
await applyCodeFile(message.content, message.fileName);
return;
}