oms/tools/src/commands/deploy.ts
liufumingren 406e5f3b58 refactor(tools): 发布工具统一到 tools(前后端同时发布 + git 约束 + 共享配置)
- 新增 tools TypeScript 发布 CLI:deploy / deploy:backend / deploy:frontend / rollback / init
- 删除 backend/script 与 frontend/scripts 旧发布脚本,前后端 npm scripts 转发到 tools
- 发布配置独立为 tools/config/deploy.config.local.cjs(模板入库,真实配置与生产 env 不入库)
- 发布受限于 git:工作区有未提交改动默认中止(--allow-dirty 放行),版本记录含 commit/branch
- 后端配置集中到 <deployRoot>/shared-config,本地 env 发布时覆盖共享配置;端口由 EGG_PORT 注入
- 前端服务器端脚本迁至 tools/remote,失败时清理未上线版本目录
- .gitignore 改为忽略 tools 本地配置与临时发布包

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-30 23:04:54 +08:00

179 lines
8.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import fs from 'node:fs';
import path from 'node:path';
import { parseArgs } from '../lib/args';
import { buildBackendArchive, buildFrontendArchive, formatBytes } from '../lib/archive';
import { buildBackendDeployScript } from '../lib/backend-remote';
import { loadDeployConfig } from '../lib/config';
import { buildFrontendDeployScript, frontendArchiveRemotePath } from '../lib/frontend-remote';
import { assertCleanWorktree, getGitInfo } from '../lib/git';
import { BACKEND_ROOT, FRONTEND_ROOT } from '../lib/paths';
import { ensureCommandAvailable, quoteForBash, runForeground, runNpm } from '../lib/shell';
import { runScp, runSsh } from '../lib/ssh';
import { getIsoTime, getNowStamp, getReleaseName } from '../lib/time';
import { recordVersion } from '../lib/version-record';
export interface DeployTargets {
backend: boolean;
frontend: boolean;
}
function runBuildCommand(command: string, cwd: string): void {
const [ bin, ...rest ] = command.trim().split(/\s+/);
if (bin === 'npm' || bin === 'npm.cmd') {
runNpm(rest, cwd);
return;
}
runForeground(bin, rest, cwd);
}
/** 上传前检查生产环境变量文件的关键项,避免误用开发环境文件覆盖线上配置 */
function warnMissingEnvKeys(filePath: string, required = [ 'MYSQL_HOST', 'MYSQL_DATABASE', 'JWT_SECRET' ]): void {
const content = fs.readFileSync(filePath, 'utf8');
const missing = required.filter(key => !new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`, 'm').test(content));
if (missing.length) {
console.warn(`[WARN] ${filePath} 缺少 ${missing.join(', ')},确认这是生产配置后再发布(该文件会覆盖服务端共享配置)。`);
}
}
/**
* 发布(默认前后端同时发布)
*
* npm run deploy # 构建前端 → 打包前后端 → 上传 → 一次 SSH 完成切换
* npm run deploy -- --dry-run # 只做本地构建与打包,打印远端脚本,不连服务器
* npm run deploy -- --skip-build # 复用已有 frontend/dist
* npm run deploy -- --allow-dirty # 允许工作区有未提交改动(发布受限于 git)
*/
export function runDeploy(args: string[], targets: DeployTargets): void {
const parsed = parseArgs(args);
const dryRun = parsed.flags.has('dry-run');
const skipBuild = parsed.flags.has('skip-build');
const allowDirty = parsed.flags.has('allow-dirty');
const config = loadDeployConfig(parsed.env, { allowMissingSecrets: dryRun });
const backend = targets.backend ? config.backend : null;
const frontend = targets.frontend ? config.frontend : null;
if (targets.backend && !backend) throw new Error('当前配置未启用 backend,无法发布后端。');
if (targets.frontend && !frontend) throw new Error('当前配置未启用 frontend,无法发布前端。');
// 发布受限于 git:默认要求工作区干净
const git = getGitInfo();
assertCleanWorktree(git, config.allowDirtyGit, allowDirty);
const targetsLabel = [ backend ? '后端' : '', frontend ? '前端' : '' ].filter(Boolean).join(' + ');
console.log(`[deploy] 环境: ${config.envName} 目标: ${config.username}@${config.host}`);
console.log(`[deploy] 分支: ${git.branch} 提交: ${git.commit}${git.dirty ? '(工作区有未提交改动)' : ''}`);
console.log(`[deploy] 发布内容: ${targetsLabel}`);
ensureCommandAvailable('tar', '请先安装 tar,Windows 10/11 通常已内置 bsdtar。');
if (!dryRun) {
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
}
if (frontend) {
if (skipBuild) {
console.log('[deploy] 跳过前端构建(--skip-build),使用现有 dist');
} else {
console.log(`[deploy] 构建前端: ${frontend.buildCommand}(cwd=frontend)`);
runBuildCommand(frontend.buildCommand, FRONTEND_ROOT);
}
}
const stamp = getNowStamp();
const releaseName = frontend ? getReleaseName() : '';
const pkg = JSON.parse(fs.readFileSync(path.join(BACKEND_ROOT, 'package.json'), 'utf8')) as { version?: string };
const backendArchive = backend ? buildBackendArchive(stamp, backend) : null;
if (backendArchive) {
console.log(`[deploy] 后端发布包: backend-${stamp}.tar.gz(${backendArchive.fileCount} 个文件,${formatBytes(backendArchive.size)})`);
}
const frontendArchive = frontend ? buildFrontendArchive(stamp, frontend) : null;
if (frontendArchive) {
console.log(`[deploy] 前端发布包: frontend-${stamp}.tar.gz(${formatBytes(frontendArchive.size)})`);
}
const remoteBackendArchive = backend ? `${backend.incomingDir}/backend-${stamp}.tar.gz` : '';
const remoteFrontendArchive = frontend ? frontendArchiveRemotePath(frontend, releaseName) : '';
const backendScript = backend
? buildBackendDeployScript(config, { stamp, remoteArchive: remoteBackendArchive, frontendRelease: releaseName })
: '';
const frontendScript = frontend ? buildFrontendDeployScript(frontend!, releaseName) : '';
// 本机生产环境变量若存在,发布前会覆盖服务端共享配置:先做一次关键项检查
const localEnvPath = backend && backend.uploadEnvFile && backend.sharedConfigDir ? backend.envFileLocalPath : '';
if (localEnvPath && fs.existsSync(localEnvPath)) warnMissingEnvKeys(localEnvPath);
if (dryRun) {
console.log('\n[deploy] --dry-run:跳过 SSH 上传与远端执行,远端脚本如下:\n');
console.log('==================== 后端脚本 ====================');
console.log(backendScript || '(未启用后端)');
console.log('==================== 前端脚本 ====================');
console.log(frontendScript || '(未启用前端)');
console.log('==================================================');
console.log('\n[deploy] --dry-run 完成(本地发布包已生成)');
if (backend) console.log(`[deploy] 后端共享配置: ${backend.sharedConfigDir || '(未配置)'}`);
return;
}
// ---- 1. 后端:先上线并通过健康检查、切换 Nginx ----
if (backend) {
console.log('[deploy] 准备后端远端目录…');
const dirs = new Set<string>([ backend.deployRoot, backend.incomingDir, backend.backupDir, backend.stateDir ]);
if (backend.sharedConfigDir) dirs.add(backend.sharedConfigDir);
runSsh(config, [ 'set -euo pipefail', `mkdir -p ${[ ...dirs ].map(quoteForBash).join(' ')}` ].join('\n'), 'pipe');
// 本地发布时覆盖服务端共享配置(后端的配置共享出来,本地有权威副本时覆盖它)
if (backend.uploadEnvFile && backend.sharedConfigDir) {
if (backend.envFileLocalPath && fs.existsSync(backend.envFileLocalPath)) {
const remoteEnvPath = `${backend.sharedConfigDir}/${backend.envFile}`;
console.log(`[deploy] 覆盖服务端共享配置: ${backend.envFileLocalPath} → ${remoteEnvPath}`);
runScp(config, backend.envFileLocalPath, remoteEnvPath);
} else {
console.log('[deploy] 本机没有生产环境变量文件,沿用服务端 shared-config 现有配置');
}
}
console.log(`[deploy] 上传后端发布包 → ${remoteBackendArchive}`);
runScp(config, backendArchive!.archivePath, remoteBackendArchive);
console.log('[deploy] 后端部署中…\n');
runSsh(config, backendScript);
}
// ---- 2. 后端就绪后再切前端(后端失败时前端完全不执行)----
if (frontend) {
console.log('[deploy] 上传前端发布包…');
runSsh(config, [ 'set -euo pipefail', `mkdir -p ${quoteForBash(`${frontend.basePath}/releases/${releaseName}`)}` ].join('\n'), 'pipe');
runScp(config, frontendArchive!.archivePath, remoteFrontendArchive);
console.log('[deploy] 前端发布中…\n');
runSsh(config, frontendScript);
}
if (backend) {
try {
recordVersion(config, {
version: pkg.version || '0.0.0',
commit: git.commit,
branch: git.branch,
env: config.envName,
dirty: git.dirty,
targets: [ 'backend', frontend ? 'frontend' : '' ].filter(Boolean),
frontendRelease: frontend ? releaseName : '',
operator: process.env.USERNAME || process.env.USER || '',
time: getIsoTime(),
files: backendArchive ? backendArchive.fileCount : 0,
size: backendArchive ? backendArchive.size : 0,
});
} catch (err) {
console.warn(`[WARN] 版本记录写入失败: ${(err as Error).message}`);
}
}
console.log('\n[deploy] ✅ 发布完成');
if (frontend) console.log(`[deploy] 前端版本: ${releaseName}`);
}