feat: 部署 TUI 支持多选服务与分层返回

This commit is contained in:
2026-09-17 10:04:23 +08:00
parent 8c56cfb0b5
commit 2ff2407e05
4 changed files with 425 additions and 247 deletions
+6 -4
View File
@@ -64,13 +64,15 @@ cd deploy
pnpm dev pnpm dev
``` ```
进入 **部署服务**,选择: 进入 **部署**,选择:
| 选项 | 说明 | | 选项 | 说明 |
|------|------| |------|------|
| 自动部署 | 编译 → 上传到服务器 → 重启容器 | | 自动部署 | 编译 → 上传 → 重启 |
| 仅编译产物 | 只编译到 `artifacts/`,不上传 | | 仅编译 | 只编译到 `artifacts/`,不上传 |
| 上传产物并重启 | 从 `artifacts/` 上传并重启,不重新编译 | | 仅上传重启 | 从 `artifacts/` 上传并重启,不重新编译 |
服务范围可选「全部」或「指定服务…」(空格多选)。子菜单按 **← 左方向键** 返回上一步。
--- ---
+202 -92
View File
@@ -1,7 +1,16 @@
#!/usr/bin/env node #!/usr/bin/env node
import { input, password as pwPrompt, select } from '@inquirer/prompts'; import { input, password as pwPrompt, select } from '@inquirer/prompts';
import { loadConfig, saveConfig, updateServiceServerConfig, getServiceConfig, getSshKeyPath, syncServerKeyAuth, resolveServiceDeployPath } from './config.js'; import {
loadConfig,
saveConfig,
updateServiceServerConfig,
getServiceConfig,
getSshKeyPath,
syncServerKeyAuth,
resolveServiceDeployPath,
getArtifactsRoot,
} from './config.js';
import { import {
buildAndDeployServices, buildAndDeployServices,
buildServicesOnly, buildServicesOnly,
@@ -12,59 +21,75 @@ import {
serviceStatus, serviceStatus,
stopService, stopService,
} from './deploy/index.js'; } from './deploy/index.js';
import { getArtifactsRoot } from './config.js';
import { ensureKeyPair, setupSSHKey, testConnection } from './ssh.js'; import { ensureKeyPair, setupSSHKey, testConnection } from './ssh.js';
import { BACK, checkboxNav, selectNav, type Nav } from './ui/nav-prompt.js';
import { printBanner, printBox, printError, printInfo, printSuccess } from './ui/render.js'; import { printBanner, printBox, printError, printInfo, printSuccess } from './ui/render.js';
import { ENV_LABELS, SERVICE_LABELS } from './types.js'; import { ENV_LABELS, SERVICE_LABELS } from './types.js';
import type { Environment, Service } from './types.js'; import type { DeployConfig, Environment, Service } from './types.js';
const ALL_SERVICES: Service[] = ['frontend', 'backend', 'license'];
async function pause() { async function pause() {
await input({ message: '按 Enter 返回' }); await input({ message: '按 Enter 返回主菜单' });
} }
async function selectEnv(): Promise<Environment> { function isExitPrompt(e: unknown): boolean {
return (e as { name?: string })?.name === 'ExitPromptError';
}
async function selectEnv(): Promise<Environment | Nav> {
const config = await loadConfig(); const config = await loadConfig();
const env = await select({ const env = await selectNav({
message: '选择环境', message: '选择环境',
choices: (['test', 'pre', 'prod'] as Environment[]).map((e) => ({ choices: (['test', 'pre', 'prod'] as Environment[]).map((e) => ({
name: `${e === config.currentEnv ? '● ' : ' '}${ENV_LABELS[e]}`, name: `${e === config.currentEnv ? '● ' : ' '}${ENV_LABELS[e]}`,
value: e, value: e,
})), })),
}); });
if (env === BACK) return BACK;
config.currentEnv = env; config.currentEnv = env;
await saveConfig(config); await saveConfig(config);
return env; return env;
} }
async function selectService(): Promise<Service> { async function selectService(): Promise<Service | Nav> {
return await select({ return await selectNav({
message: '选择服务', message: '选择服务',
choices: [ choices: [
{ name: '前端', value: 'frontend' }, { name: '前端', value: 'frontend' as Service },
{ name: '后端', value: 'backend' }, { name: '后端', value: 'backend' as Service },
{ name: '许可证服务', value: 'license' }, { name: '许可证', value: 'license' as Service },
],
}) as Service;
}
async function selectServices(): Promise<Service[]> {
const selected = await select({
message: '选择服务',
choices: [
{ name: '全部服务', value: 'all' as any },
{ name: '前端', value: 'frontend' },
{ name: '后端', value: 'backend' },
{ name: '许可证服务', value: 'license' },
], ],
}); });
if (selected === 'all') return ['frontend', 'backend', 'license'];
return [selected as Service];
} }
function showServiceHosts(config: Awaited<ReturnType<typeof loadConfig>>): string { /** 空格多选服务;← 返回上一步 */
async function selectServicesMulti(): Promise<Service[] | Nav> {
const scope = await selectNav({
message: '部署范围',
choices: [
{ name: '全部服务', value: 'all' as const, description: '前端 + 后端 + 许可证' },
{ name: '指定服务…', value: 'pick' as const, description: '空格多选' },
],
});
if (scope === BACK) return BACK;
if (scope === 'all') return [...ALL_SERVICES];
const picked = await checkboxNav({
message: '勾选服务',
choices: [
{ name: '前端', value: 'frontend' as Service },
{ name: '后端', value: 'backend' as Service },
{ name: '许可证', value: 'license' as Service },
],
required: true,
});
return picked;
}
function showServiceHosts(config: DeployConfig): string {
const env = config.currentEnv; const env = config.currentEnv;
const services: Service[] = ['frontend', 'backend', 'license']; return ALL_SERVICES.map((s) => {
return services.map((s) => {
const cfg = config.services[s][env]; const cfg = config.services[s][env];
const resolved = resolveServiceDeployPath(cfg, s, env); const resolved = resolveServiceDeployPath(cfg, s, env);
return ` ${SERVICE_LABELS[s]}: ${cfg.server.host} → ${resolved}`; return ` ${SERVICE_LABELS[s]}: ${cfg.server.host} → ${resolved}`;
@@ -72,35 +97,41 @@ function showServiceHosts(config: Awaited<ReturnType<typeof loadConfig>>): strin
} }
async function configureService() { async function configureService() {
const config = await loadConfig(); while (true) {
const service = await selectService(); const service = await selectService();
if (service === BACK) return;
const env = await selectEnv(); const env = await selectEnv();
if (env === BACK) continue;
while (true) {
const config = await loadConfig();
const cfg = config.services[service][env]; const cfg = config.services[service][env];
const srv = cfg.server; const srv = cfg.server;
console.clear(); console.clear();
printBox(`${SERVICE_LABELS[service]} · ${ENV_LABELS[env]} 配置`, [ printBox(`${SERVICE_LABELS[service]} · ${ENV_LABELS[env]}`, [
`服务器: ${srv.host}:${srv.port}`, `服务器: ${srv.host}:${srv.port}`,
`用户: ${srv.username}`, `用户: ${srv.username}`,
`部署根目录: ${srv.deployPath}`, `部署根: ${srv.deployPath}`,
`实际目录: ${resolveServiceDeployPath(cfg, service, env)}`, `实际目录: ${resolveServiceDeployPath(cfg, service, env)}`,
`端口: ${cfg.port}`, `端口: ${cfg.port}`,
`认证方式: ${srv.authType === 'key' ? '密钥' : '密码'}`, `认证: ${srv.authType === 'key' ? '密钥' : '密码'}`,
].join('\n')); ].join('\n'));
const action = await select({ const action = await selectNav({
message: '配置操作', message: '配置项',
choices: [ choices: [
{ name: '修改服务器地址', value: 'host' }, { name: '服务器地址', value: 'host' as const },
{ name: '修改端口', value: 'port' }, { name: 'SSH 端口', value: 'port' as const },
{ name: '修改服务端口', value: 'svcPort' }, { name: '服务端口', value: 'svcPort' as const },
{ name: '修改用户名', value: 'username' }, { name: '用户名', value: 'username' as const },
{ name: '修改部署根目录', value: 'deployPath' }, { name: '部署根目录', value: 'deployPath' as const },
{ name: '测试 SSH 连接', value: 'test' }, { name: '测试 SSH', value: 'test' as const },
{ name: '配置 SSH 密钥 (首次免密)', value: 'setupKey' }, { name: '配置免密密钥', value: 'setupKey' as const, description: '首次上传公钥' },
{ name: '返回', value: 'back' },
], ],
}); });
if (action === BACK) break;
switch (action) { switch (action) {
case 'host': { case 'host': {
@@ -126,12 +157,9 @@ async function configureService() {
} }
case 'deployPath': { case 'deployPath': {
const hint = service === 'frontend' const hint = service === 'frontend'
? `部署根目录(实际为 根目录/ecom-dmb-${env}/index)` ? '部署根(实际为 根/ecom-dmb-{env}/index)'
: `部署根目录(实际为 根目录/ecom-dmb/${service}/${env})`; : '部署根(实际为 根/ecom-dmb/{service}/{env})';
const d = await input({ const d = await input({ message: hint, default: srv.deployPath });
message: hint,
default: srv.deployPath,
});
await updateServiceServerConfig(service, env, { deployPath: d }); await updateServiceServerConfig(service, env, { deployPath: d });
break; break;
} }
@@ -139,48 +167,86 @@ async function configureService() {
const ok = await testConnection(srv); const ok = await testConnection(srv);
if (ok) printSuccess('SSH 连接成功'); if (ok) printSuccess('SSH 连接成功');
else printError('SSH 连接失败'); else printError('SSH 连接失败');
await pause();
break; break;
} }
case 'setupKey': { case 'setupKey': {
const pwd = await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true }); const pwd = await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true });
try { try {
await setupSSHKey(srv, pwd); await setupSSHKey(srv, pwd);
await syncServerKeyAuth(srv.host, srv.username, { authType: 'key', keyPath: getSshKeyPath() }); await syncServerKeyAuth(srv.host, srv.username, {
authType: 'key',
keyPath: getSshKeyPath(),
});
} catch (e: any) { } catch (e: any) {
printError(`密钥配置失败: ${e.message}`); printError(`密钥配置失败: ${e.message}`);
} }
await pause();
break; break;
} }
} }
}
}
} }
async function deployMenu() { async function deployMenu() {
type DeployMode = 'auto' | 'buildOnly' | 'uploadOnly';
type Step = 'mode' | 'services' | 'confirm';
let step: Step = 'mode';
let deployMode: DeployMode = 'auto';
let services: Service[] = [];
const config = await loadConfig(); const config = await loadConfig();
const env = config.currentEnv; const env = config.currentEnv;
printBox('当前环境', `${ENV_LABELS[env]}\n${showServiceHosts(config)}`, 'yellow'); printBox('当前环境', `${ENV_LABELS[env]}\n${showServiceHosts(config)}`, 'yellow');
const deployMode = await select({ while (true) {
if (step === 'mode') {
const mode = await selectNav({
message: '部署方式', message: '部署方式',
choices: [ choices: [
{ name: '自动部署(编译 + 上传 + 重启)', value: 'auto' }, { name: '自动部署', value: 'auto' as const, description: '编译 → 上传 → 重启' },
{ name: '仅编译产物(不上传,输出到 artifacts/)', value: 'buildOnly' }, { name: '仅编译', value: 'buildOnly' as const, description: '产物到 artifacts/,不上传' },
{ name: '上传产物并重启(从 artifacts/,不编译)', value: 'uploadOnly' }, { name: '仅上传重启', value: 'uploadOnly' as const, description: '用已有 artifacts/,不编译' },
{ name: '取消', value: 'cancel' },
], ],
}); });
if (deployMode === 'cancel') return; if (mode === BACK) return;
deployMode = mode;
const services = await selectServices(); step = 'services';
printBox('待部署服务', services.map((s) => `${SERVICE_LABELS[s]} → ${config.services[s][env].server.host}`).join('\n'), 'cyan'); continue;
}
if (step === 'services') {
const picked = await selectServicesMulti();
if (picked === BACK) {
step = 'mode';
continue;
}
services = picked;
printBox(
'待部署',
services.map((s) => `${SERVICE_LABELS[s]} → ${config.services[s][env].server.host}`).join('\n'),
'cyan',
);
if (deployMode === 'buildOnly') { if (deployMode === 'buildOnly') {
printInfo(`产物目录: ${getArtifactsRoot()}`); printInfo(`产物目录: ${getArtifactsRoot()}`);
} }
step = 'confirm';
continue;
}
const ok = await select({ const ok = await selectNav({
message: '确认执行?', message: '确认执行?',
choices: [{ name: '开始', value: 'go' }, { name: '取消', value: 'cancel' }], choices: [
{ name: '开始', value: 'go' as const },
{ name: '取消', value: 'cancel' as const },
],
}); });
if (ok === BACK) {
step = 'services';
continue;
}
if (ok === 'cancel') return; if (ok === 'cancel') return;
const onPassword = async (s: Service) => { const onPassword = async (s: Service) => {
@@ -201,29 +267,35 @@ async function deployMenu() {
} catch (e: any) { } catch (e: any) {
printError(`操作失败: ${e.message}`); printError(`操作失败: ${e.message}`);
} }
return;
}
} }
async function serviceMenu() { async function serviceMenu() {
while (true) {
const service = await selectService(); const service = await selectService();
if (service === BACK) return;
const config = await loadConfig(); const config = await loadConfig();
const cfg = getServiceConfig(config, service); const cfg = getServiceConfig(config, service);
const srv = cfg.server; const srv = cfg.server;
const action = await select({ while (true) {
message: `${SERVICE_LABELS[service]} 管理 (${srv.host})`, const action = await selectNav({
message: `${SERVICE_LABELS[service]} · ${srv.host}`,
choices: [ choices: [
{ name: '查看状态', value: 'status' }, { name: '状态', value: 'status' as const },
{ name: '查看日志', value: 'logs' }, { name: '日志', value: 'logs' as const },
{ name: '重启服务', value: 'restart' }, { name: '重启', value: 'restart' as const },
{ name: '停止服务', value: 'stop' }, { name: '停止', value: 'stop' as const },
{ name: '检查 Docker 环境', value: 'checkDocker' }, { name: '检查 Docker', value: 'checkDocker' as const },
{ name: '返回', value: 'back' },
], ],
}); });
if (action === 'back') return; if (action === BACK) break;
console.clear(); console.clear();
const onPassword = async () => await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true }); const onPassword = async () =>
await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true });
try { try {
switch (action) { switch (action) {
@@ -251,25 +323,32 @@ async function serviceMenu() {
} catch (e: any) { } catch (e: any) {
printError(`操作失败: ${e.message}`); printError(`操作失败: ${e.message}`);
} }
await pause();
console.clear();
}
}
} }
async function sshMenu() { async function sshMenu() {
const config = await loadConfig(); while (true) {
const service = await selectService(); const service = await selectService();
if (service === BACK) return;
const config = await loadConfig();
const env = config.currentEnv; const env = config.currentEnv;
const srv = config.services[service][env].server; const srv = config.services[service][env].server;
const action = await select({ while (true) {
message: `${SERVICE_LABELS[service]} SSH 管理 (${srv.host})`, const action = await selectNav({
message: `SSH · ${SERVICE_LABELS[service]} (${srv.host})`,
choices: [ choices: [
{ name: '查看 SSH 密钥状态', value: 'status' }, { name: '密钥状态', value: 'status' as const },
{ name: '生成 SSH 密钥对', value: 'genKey' }, { name: '生成密钥对', value: 'genKey' as const },
{ name: '上传公钥到服务器', value: 'uploadKey' }, { name: '上传公钥', value: 'uploadKey' as const },
{ name: '测试连接', value: 'test' }, { name: '测试连接', value: 'test' as const },
{ name: '返回', value: 'back' },
], ],
}); });
if (action === 'back') return; if (action === BACK) break;
console.clear(); console.clear();
switch (action) { switch (action) {
@@ -288,7 +367,10 @@ async function sshMenu() {
const pwd = await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true }); const pwd = await pwPrompt({ message: `输入 ${srv.host} 的 SSH 密码`, mask: true });
try { try {
await setupSSHKey(srv, pwd); await setupSSHKey(srv, pwd);
await syncServerKeyAuth(srv.host, srv.username, { authType: 'key', keyPath: getSshKeyPath() }); await syncServerKeyAuth(srv.host, srv.username, {
authType: 'key',
keyPath: getSshKeyPath(),
});
} catch (e: any) { } catch (e: any) {
printError(`上传失败: ${e.message}`); printError(`上传失败: ${e.message}`);
} }
@@ -304,9 +386,13 @@ async function sshMenu() {
break; break;
} }
} }
await pause();
console.clear();
}
}
} }
async function mainMenu() { async function mainMenu(): Promise<'continue' | 'exit'> {
console.clear(); console.clear();
printBanner(); printBanner();
@@ -314,40 +400,64 @@ async function mainMenu() {
const env = config.currentEnv; const env = config.currentEnv;
printInfo(`当前环境: ${ENV_LABELS[env]}`); printInfo(`当前环境: ${ENV_LABELS[env]}`);
console.log(showServiceHosts(config)); console.log(showServiceHosts(config));
printInfo('提示: 子菜单按 ← 返回上一步');
const action = await select({ const action = await select({
message: '主菜单', message: '主菜单',
choices: [ choices: [
{ name: '部署服务', value: 'deploy' }, { name: '部署', value: 'deploy' },
{ name: '服务管理', value: 'service' }, { name: '服务管理', value: 'service' },
{ name: '配置服务', value: 'config' }, { name: '配置', value: 'config' },
{ name: 'SSH 密钥管理', value: 'ssh' }, { name: 'SSH', value: 'ssh' },
{ name: '切换环境', value: 'switchEnv' }, { name: '切换环境', value: 'switchEnv' },
{ name: '退出', value: 'exit' }, { name: '退出', value: 'exit' },
], ],
theme: {
style: {
keysHelpTip: () => '↑↓ 选择 · ⏎ 确认',
},
},
}); });
switch (action) { switch (action) {
case 'deploy': console.clear(); await deployMenu(); break; case 'deploy':
case 'service': console.clear(); await serviceMenu(); break; console.clear();
case 'config': await configureService(); break; await deployMenu();
case 'ssh': await sshMenu(); break; break;
case 'service':
console.clear();
await serviceMenu();
break;
case 'config':
await configureService();
break;
case 'ssh':
await sshMenu();
break;
case 'switchEnv': { case 'switchEnv': {
const newEnv = await selectEnv(); const newEnv = await selectEnv();
if (newEnv !== BACK) {
printSuccess(`已切换到: ${ENV_LABELS[newEnv]}`); printSuccess(`已切换到: ${ENV_LABELS[newEnv]}`);
}
break; break;
} }
case 'exit': process.exit(0); case 'exit':
return 'exit';
} }
return 'continue';
} }
async function main() { async function main() {
while (true) { while (true) {
try { try {
await mainMenu(); const result = await mainMenu();
if (result === 'exit') process.exit(0);
await pause(); await pause();
} catch (e: any) { } catch (e: any) {
if (e?.name === 'ExitPromptError') process.exit(0); if (isExitPrompt(e)) {
printInfo('已取消');
continue;
}
printError(String(e?.message || e)); printError(String(e?.message || e));
await pause(); await pause();
} }
+4 -4
View File
@@ -34,11 +34,11 @@ export interface DeployConfig {
export const SERVICE_LABELS: Record<Service, string> = { export const SERVICE_LABELS: Record<Service, string> = {
frontend: '前端', frontend: '前端',
backend: '后端', backend: '后端',
license: '许可证服务', license: '许可证',
}; };
export const ENV_LABELS: Record<Environment, string> = { export const ENV_LABELS: Record<Environment, string> = {
test: '测试环境', test: '测试',
pre: '预发布环境', pre: '预发',
prod: '生产环境', prod: '生产',
}; };
+66
View File
@@ -0,0 +1,66 @@
import { checkbox, select } from '@inquirer/prompts';
import type { Key } from 'node:readline';
/** 导航:左方向键返回 */
export const BACK = '__back__' as const;
export type Nav = typeof BACK;
type Cancellable<T> = Promise<T> & { cancel: () => void };
function isCancelPrompt(e: unknown): boolean {
return (e as { name?: string })?.name === 'CancelPromptError';
}
/**
* 运行可取消的 inquirer prompt:← 左键 → cancel → 返回 BACK。
*/
export async function withLeftBack<T>(start: () => Cancellable<T>): Promise<T | Nav> {
const prompt = start();
const onKeypress = (_input: string, key: Key) => {
// 左方向键;忽略带修饰键,避免误触
if (key?.name === 'left' && !key.ctrl && !key.meta && !key.shift) {
prompt.cancel();
}
};
process.stdin.on('keypress', onKeypress);
try {
return await prompt;
} catch (e) {
if (isCancelPrompt(e)) return BACK;
throw e;
} finally {
process.stdin.off('keypress', onKeypress);
}
}
const selectHelp = {
style: {
keysHelpTip: () => '↑↓ 选择 · ⏎ 确认 · ← 返回',
},
} as const;
const checkboxHelp = {
style: {
keysHelpTip: () => '↑↓ 移动 · 空格 勾选 · a 全选 · ⏎ 确认 · ← 返回',
},
} as const;
/** select:← 返回 BACK */
export function selectNav<Value>(config: Parameters<typeof select<Value>>[0]) {
return withLeftBack(() =>
select({
...config,
theme: { ...selectHelp, ...(config.theme as object | undefined) },
}),
);
}
/** checkbox:← 返回 BACK */
export function checkboxNav<Value>(config: Parameters<typeof checkbox<Value>>[0]) {
return withLeftBack(() =>
checkbox({
...config,
theme: { ...checkboxHelp, ...(config.theme as object | undefined) },
}),
);
}