feat: support first connect in remote environment

This commit is contained in:
Levi Yan
2025-05-06 23:05:00 +08:00
parent e4d9d2b3b7
commit 70fa291e37
3 changed files with 141 additions and 37 deletions

View File

@@ -69,7 +69,7 @@ export default class DSHome {
break; break;
} }
case 'firstOpenRemoteFolder': case 'firstOpenRemoteFolder':
await this.remoteContainer.firstConnect(data.host, data.username, data.port) await this.remoteContainer.firstConnect(data.host, data.username, data.port, this.context)
.then((_res) => { .then((_res) => {
if (_res == 'success') { if (_res == 'success') {
// only success then open folder // only success then open folder

View File

@@ -43,12 +43,12 @@ export class DevStarExtension {
// 如果没有用户登录,则直接登录; // 如果没有用户登录,则直接登录;
const res = await this.user.login(access_token, devstar_username) const res = await this.user.login(access_token, devstar_username)
if (res === 'ok') { if (res === 'ok') {
await this.remoteContainer.firstOpenProject(container_host, container_port, container_username, project_path) await this.remoteContainer.firstOpenProject(container_host, container_port, container_username, project_path, this.context)
} }
} else if (devstar_username === this.user.getUsernameFromLocal()) { } else if (devstar_username === this.user.getUsernameFromLocal()) {
// 如果同用户已经登录,则忽略; // 如果同用户已经登录,则忽略;
// 直接打开项目 // 直接打开项目
await this.remoteContainer.firstOpenProject(container_host, container_port, container_username, project_path) await this.remoteContainer.firstOpenProject(container_host, container_port, container_username, project_path, this.context)
} else { } else {
// 如果不是同用户,可以选择切换用户,或者不切换登录用户,直接打开容器 // 如果不是同用户,可以选择切换用户,或者不切换登录用户,直接打开容器
const selection = await vscode.window.showWarningMessage(`已登录用户:${this.user.getUsernameFromLocal()},是否切换用户?`, const selection = await vscode.window.showWarningMessage(`已登录用户:${this.user.getUsernameFromLocal()},是否切换用户?`,
@@ -57,7 +57,7 @@ export class DevStarExtension {
// 如果没有用户登录,则直接登录; // 如果没有用户登录,则直接登录;
const res = await this.user.login(access_token, devstar_username) const res = await this.user.login(access_token, devstar_username)
if (res === 'ok') { if (res === 'ok') {
await this.remoteContainer.firstOpenProject(container_host, container_port, container_username, project_path) await this.remoteContainer.firstOpenProject(container_host, container_port, container_username, project_path, this.context)
} }
} else if (selection === 'No') { } else if (selection === 'No') {
await openProjectWithoutLogging(container_host, container_port, container_username, project_path); await openProjectWithoutLogging(container_host, container_port, container_username, project_path);

View File

@@ -7,6 +7,7 @@ const { NodeSSH } = require('node-ssh')
import * as utils from './utils'; import * as utils from './utils';
import User from './user'; import User from './user';
import DevstarAPIHandler from './devstar-api';
export default class RemoteContainer { export default class RemoteContainer {
private user: User; private user: User;
@@ -15,8 +16,8 @@ export default class RemoteContainer {
this.user = user this.user = user
} }
async firstOpenProject(host: string, port: number, username: string, path: string) { async firstOpenProject(host: string, port: number, username: string, path: string, context: vscode.ExtensionContext) {
await this.firstConnect(host, username, port) await this.firstConnect(host, username, port, context)
.then((res) => { .then((res) => {
if (res === 'success') { if (res === 'success') {
// only success then open folder // only success then open folder
@@ -26,7 +27,7 @@ export default class RemoteContainer {
} }
// connect with key // connect with key
async firstConnect(host: string, username: string, port: number): Promise<string> { async firstConnect(hostname: string, username: string, port: number, context: vscode.ExtensionContext): Promise<string> {
return new Promise(async (resolve) => { return new Promise(async (resolve) => {
const ssh = new NodeSSH(); const ssh = new NodeSSH();
vscode.window.withProgress({ vscode.window.withProgress({
@@ -34,21 +35,31 @@ export default class RemoteContainer {
title: vscode.l10n.t("Installing vscode-server and devstar extension in container"), title: vscode.l10n.t("Installing vscode-server and devstar extension in container"),
cancellable: false cancellable: false
}, async (progress) => { }, async (progress) => {
try { if (vscode.env.remoteName) {
// connect with key // 远程环境
await ssh.connect({ // 检查公私钥是否存在,如果不存在,需要创建
host: host, if (!this.user.existUserPrivateKey() || !this.user.existUserPublicKey()) {
username: username, this.user.createUserSSHKey()
port: port, // 上传公钥
privateKeyPath: this.user.getUserPrivateKeyPath() const devstarAPIHandler = new DevstarAPIHandler()
}); await devstarAPIHandler.uploadUserPublicKey(this.user)
progress.report({ message: vscode.l10n.t("Connected! Start installation") }); }
// install vscode-server and devstar extension try {
const vscodeCommitId = await utils.getVsCodeCommitId() // 第一次连接
if ("" != vscodeCommitId) { await ssh.connect({
const vscodeServerUrl = `https://vscode.download.prss.microsoft.com/dbazure/download/stable/${vscodeCommitId}/vscode-server-linux-x64.tar.gz` host: hostname,
const installVscodeServerScript = ` username: username,
port: port,
privateKeyPath: this.user.getUserPrivateKeyPath()
});
progress.report({ message: vscode.l10n.t("Connected! Start installation") });
// 安装vscode-server and devstar extension
const vscodeCommitId = await utils.getVsCodeCommitId()
if ("" != vscodeCommitId) {
const vscodeServerUrl = `https://vscode.download.prss.microsoft.com/dbazure/download/stable/${vscodeCommitId}/vscode-server-linux-x64.tar.gz`
const installVscodeServerScript = `
mkdir -p ~/.vscode-server/bin/${vscodeCommitId} && \\ mkdir -p ~/.vscode-server/bin/${vscodeCommitId} && \\
if [ "$(ls -A ~/.vscode-server/bin/${vscodeCommitId})" ]; then if [ "$(ls -A ~/.vscode-server/bin/${vscodeCommitId})" ]; then
~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar ~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar
@@ -61,18 +72,98 @@ export default class RemoteContainer {
~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar ~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar
fi fi
`; `;
await ssh.execCommand(installVscodeServerScript); await ssh.execCommand(installVscodeServerScript);
console.log("vscode-server and extension installed"); console.log("vscode-server and extension installed");
vscode.window.showInformationMessage(vscode.l10n.t('Installation completed!')); vscode.window.showInformationMessage(vscode.l10n.t('Installation completed!'));
}
await ssh.dispose();
// ssh信息存储到ssh config file中
// 远程环境利用global state中记录的localSystemName来决定执行的命令
const localSystemName = utils.getLocalSystemName(context)
const localSSHConfigPath = utils.getLocalSSHConfigPath(context);
const privateKeyPath = this.user.getLocalUserPrivateKeyPath();
const host = `${hostname}-${port}` // host: hostname-port
const newSShConfigContent =
`\nHost ${host}\n HostName ${hostname}\n Port ${port}\n User ${username}\n PreferredAuthentications publickey\n IdentityFile ${privateKeyPath}\n `;
let commandToAppend: string;
const delimiter = `EOF_SSH_CONFIG_${Date.now()}`; // 使用一个唯一的分隔符用于 here-docs (Unix) 或 here-strings (PowerShell)
if (localSystemName === "win32") {
// --- Windows 平台 ---
// 使用 PowerShell 的 Here-String (@'...'@) 来保证多行文本输入的健壮性
// @'...'@ 内的内容会按字面解释,减少转义问题
const escapedContent = newSShConfigContent.replace(/'/g, "''"); // 对内容中的单引号进行转义(替换为两个单引号),以防万一变量值包含单引号
const psTargetPath = localSSHConfigPath;
// 将内容包裹在 @'\n...\n'@ 中,确保前后有换行
commandToAppend = `Add-Content -Path '${psTargetPath}' -Value @'\n${escapedContent}\n'@`;
} else if (localSystemName === "darwin" || localSystemName === "linux") {
// --- Linux, macOS, 或其他类 Unix 系统 ---
const unixTargetPath = `"${localSSHConfigPath}"`;
commandToAppend = `cat << '${delimiter}' >> ${unixTargetPath}
${newSShConfigContent}
${delimiter}
`;
}
// 通过local terminal命令行写入
vscode.commands.executeCommand('workbench.action.terminal.newLocal').then(() => {
const terminal = vscode.window.terminals[vscode.window.terminals.length - 1];
if (terminal) {
terminal.sendText(commandToAppend, true);
}
})
resolve('success')
} catch (error) {
console.error('Failed to install vscode-server and extension: ', error);
await ssh.dispose();
} }
} else {
// 本地环境
try {
// connect with key
await ssh.connect({
host: hostname,
username: username,
port: port,
privateKeyPath: this.user.getUserPrivateKeyPath()
});
progress.report({ message: vscode.l10n.t("Connected! Start installation") });
await ssh.dispose(); // install vscode-server and devstar extension
await this.storeHostInfo(host, port, username) const vscodeCommitId = await utils.getVsCodeCommitId()
if ("" != vscodeCommitId) {
const vscodeServerUrl = `https://vscode.download.prss.microsoft.com/dbazure/download/stable/${vscodeCommitId}/vscode-server-linux-x64.tar.gz`
const installVscodeServerScript = `
mkdir -p ~/.vscode-server/bin/${vscodeCommitId} && \\
if [ "$(ls -A ~/.vscode-server/bin/${vscodeCommitId})" ]; then
~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar
else
wget ${vscodeServerUrl} -O vscode-server-linux-x64.tar.gz && \\
mv vscode-server-linux-x64.tar.gz ~/.vscode-server/bin/${vscodeCommitId} && \\
cd ~/.vscode-server/bin/${vscodeCommitId} && \\
tar -xvzf vscode-server-linux-x64.tar.gz --strip-components 1 && \\
rm vscode-server-linux-x64.tar.gz && \\
~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar
fi
`;
await ssh.execCommand(installVscodeServerScript);
console.log("vscode-server and extension installed");
vscode.window.showInformationMessage(vscode.l10n.t('Installation completed!'));
}
resolve('success') await ssh.dispose();
} catch (error) {
console.error('Failed to install vscode-server and extension: ', error); // only connect successfully then save the host info
await ssh.dispose(); await this.storeHostInfo(hostname, port, username)
resolve('success')
} catch (error) {
console.error('Failed to install vscode-server and extension: ', error);
await ssh.dispose();
}
} }
}); });
}); });
@@ -107,14 +198,27 @@ export default class RemoteContainer {
} }
openRemoteFolder(host: string, port: number, username: string, path: string): void { openRemoteFolder(hostname: string, port: number, username: string, path: string): void {
var host = `${host}-${port}` if (vscode.env.remoteName) {
const command = `code --remote ssh-remote+${username}@${host}:${port} ${path} --reuse-window` // 远程环境打开local terminal
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`); vscode.commands.executeCommand('workbench.action.terminal.newLocal').then(() => {
terminal.show(true); // 获取最后一个打开的终端实例
terminal.sendText(command); const terminal = vscode.window.terminals[vscode.window.terminals.length - 1];
if (terminal) {
var host = `${hostname}-${port}`
// 在新窗口打开
terminal.sendText(`code --remote ssh-remote+${username}@${host}:${port} ${path} --new-window`)
}
})
} else {
// 本地环境
var host = `${hostname}-${port}`
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`);
terminal.show(true);
// 在原窗口打开
terminal.sendText(`code --remote ssh-remote+${username}@${host}:${port} ${path} --reuse-window`);
}
} }
} }