dockervisual-studio-codevscode-extensions

How to Open VSCode Project in Container Programmatically from an Extension?


I'm developing a VS Code extension that allows users to create or open existing projects directly in a container. The project is guaranteed to have a devcontainer.json file, and I would like to automatically open it in the container mode.

I discovered that the Remote Containers extension has a command remote-containers.openFolderInContainerInCurrentWindow listed in its package.json. However, when I attempt to call this command, it doesn’t seem to work as expected.

async function openProject() {
    const folderUri = await selectProjectFolder('Please select a folder', 'Open')
    if (folderUri) {
        var containerExtension =  extensions.getExtension('ms-vscode-remote.remote-containers')
        if (containerExtension) {
            window.showInformationMessage('containerExtension exists')
            if (containerExtension.isActive == false) {
                window.showInformationMessage('containerExtension not active')
                containerExtension.activate().then(() => {
                    commands.executeCommand('remote-containers.openFolderInContainerInCurrentWindow', folderUri).then(() => {
                        window.showInformationMessage('containerExtension command success 1')
                    }, (error) => {
                        window.showInformationMessage('containerExtension command failed 1: ' + error)
                    })
                }, () => {
                    window.showInformationMessage('containerExtension activation failed')
                })
            } else {
                window.showInformationMessage('containerExtension active')
                commands.executeCommand('remote-containers.openFolderInContainerInCurrentWindow', folderUri).then(() => {
                    window.showInformationMessage('containerExtension command success 2')
                }, (error) => {
                    window.showInformationMessage('containerExtension command failed 2: ' + error)
                })
            }
        } else {
            window.showInformationMessage('containerExtension not found')
        }
    }
}

When I run this, the logs indicate:

The standard built-in command vscode.openFolder works as a workaround, but it requires the user to manually click "Reopen in Container" after the project is opened, which adds an extra step that I want to avoid.

Has anyone successfully called remote-containers.openFolderInContainerInCurrentWindow from their extension? Any guidance or tips on how to properly invoke this command would be greatly appreciated.

Thanks in advance!


Solution

  • The right command is just

    commands.executeCommand('remote-containers.openFolder', folderUri)
    

    so it opens the project in container mode in the same window.