VS Code: Use the list of multi-root workspace folders during dev container build

3.6k Views Asked by At

I have a ~/projects/ directory with a bunch of cloned Git repos in it. I like to select subsets of these and save them as VS Code multi-root workspaces as ~/projects/*.code-workspace.

I also use a dev container, configured with ~/projects/.devcontainer.json so that all the workspaces find it automatically.

When I build a dev container, I would love to be able to run some initialization logic with the input being the list of folders in the open workspace.

I can use ${containerWorkspaceFolder} in .devcontainer.json, but this gives me ~/projects, not the exact .code-workspace file, and there are multiple .code-workspace files in the directory. If I could get the path of the current .code-workspace file, I could parse the json and get the folder list, but it seems I can only get the parent folder.

I tried setting terminal.integrated.env.linux in foo.code-workspace to set a per-workspace environment variable CODE_WORKSPACE_FILE=~/projects/foo.code-workspace, but it isn't visible to the devcontainer build, only in integrated terminals I open after the workspace is already open in the container.

I see that there is a workspace.workspaceFolders() method in the vscode extension API. I don't want to write an extension just to expose that value to the devcontainers system, but maybe that's the only way currently.

Any other ideas?

1

There are 1 best solutions below

0
On

It isn't exactly what you asked for, but you can use code-workspace files in a devcontainer if you mount your source code in devcontainer.json. You can use the mounts property in devcontainer.json (https://containers.dev/implementors/json_reference/).

First, add the following to your devcontainer.json file:

"mounts": [
  {"source":"~/projects","/projects","type":"bind"},
],

Second move your .devcontainer folder to an empty directory. For example, you could make a folder named for the container template or your project in home directory, something like ~/nodejs-postgres. Copy your *.code-workspace files into the .devcontainer folder. You should have the following folder structure:

- ~/nodejs-postgres
  - .devcontainer
    - devcontainer.json
    - project1.code-workspace
    - project2.code-workspace
    - ...

Next, edit the code-workspace files so the paths use /projects instead of ~/projects.

Finally open ~/nodejs-postgres in a devcontainer. After the container is built and ready to use, you should have a code window with just the devcontainer folder open. Your entire projects folder is mounted in the container, but the folders aren't open in vscode.

At this point, you can use the Add Folder to Workspace command to add a folder to the current workspace in the devcontainer or you can open one of your code-workspace files in an editor and click the Open Workspace button that comes up. After clicking the button, it will open the mounted project folders in the container.