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. 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. 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. Any pointers are appreciated.
Asked
Active
Viewed 1,317 times
1

Manas
- 521
- 8
- 26
-
create the file and read the extension file content with `workspace.fs` and edit/write this to the new file, there is an API function that fives you the path of the extension (If my memory is correct) – rioV8 Dec 14 '20 at 10:28
-
Can you confirm if this is how you created the extension? I am stuck in a similar issue and wondering what's the best way to copy files is. – Grimson Mar 14 '22 at 06:11
-
Yes, I used a simply copy command mapped to an action. – Manas Mar 16 '22 at 02:48
1 Answers
1
I created a function copyFile
that can copy file from within a VSCode extension to the workspace at the provided destination.
You can use WorkspaceEdit and FileSystem VS Code API to achieve this task as shown below.
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 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) {});
...
}

Abhinav Sharma
- 101
- 6