简体   繁体   English

如何将 VSCode 扩展中的文件复制到工作区?

[英]How do I copy files from within a VSCode extension to the workspace?

I have certain files within the VSCode extension src folder that I would like to copy into the root of the workspace on running a certain command.我在 VSCode 扩展src文件夹中有某些文件,我想在运行某个命令时将它们复制到工作区的根目录中。 Once this is working I would also like to extend this to copy other static files with specific content into other sub-folders within the workspace.一旦这工作正常,我还想扩展它以将具有特定内容的其他 static 文件复制到工作区中的其他子文件夹中。 I found a way to create new files here .我在这里找到了一种创建新文件的方法。 However, I am unable to find a way to copy entire files bundled within the extension into the workspace.但是,我无法找到将扩展中捆绑的整个文件复制到工作区的方法。 Looking at the MSFT documentation here , I cannot find anything that would work for my use case.查看此处的 MSFT 文档,我找不到适合我的用例的任何内容。 Any pointers are appreciated.任何指针表示赞赏。

I created a function copyFile that can copy file from within a VSCode extension to the workspace at the provided destination.我创建了一个 function copyFile ,它可以将文件从 VSCode 扩展名复制到提供的目的地的工作区。

You can use WorkspaceEdit and FileSystem VS Code API to achieve this task as shown below.您可以使用WorkspaceEditFileSystem VS Code API 来完成此任务,如下所示。

async function copyFile(
  vscode,
  context,
  outputChannel,
  sourcePath,
  destPath,
  callBack
) {
  try {
    const wsedit = new vscode.WorkspaceEdit();
    const wsPath = vscode.workspace.workspaceFolders[0].uri.fsPath;
    const data = await vscode.workspace.fs.readFile(
      vscode.Uri.file(context.asAbsolutePath(sourcePath))
    );
    const filePath = vscode.Uri.file(wsPath + destPath);
    wsedit.createFile(filePath, { ignoreIfExists: true });
    await vscode.workspace.fs.writeFile(filePath, data);
    let isDone = await vscode.workspace.applyEdit(wsedit);
    if(isDone) {
      outputChannel.appendLine(`File created successfully: ${destPath}`);
      callBack(null, true);
    }
  } catch (err) {
    outputChannel.appendLine(`ERROR: ${err}`);
    callBack(err, false);
  }
}

Sample function call:样品 function 调用:

function activate(context) {
  ...
  let testChannel = vscode.window.createOutputChannel("TestChannel");
  // copy tasks.json file from vs code extension to the destination workspace
  copyFile(vscode, context, testChannel, 
           'assets/tasks.json', '/.vscode/tasks.json', function(err, res) {});
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM