#!/usr/bin/env node /** * 跨平台发布脚本(Windows / macOS / Linux 通用) * * 等价于原 deploy.sh,改用 Node.js 实现,使 Windows 开发环境无需安装 sh/bash。 * 依赖本机已安装:ssh、scp、tar(Windows 10 1803+ 自带 OpenSSH 客户端与 bsdtar)。 * * 用法:npm run deploy */ import { spawnSync } from 'node:child_process'; import { existsSync, readFileSync, rmSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); // --- 配置(读取独立配置文件,该文件不纳入版本控制) --- const CONFIG_PATH = path.join(__dirname, 'deploy.config.json'); if (!existsSync(CONFIG_PATH)) { console.error('❌ 缺少配置文件 deploy.config.json'); console.error(' 请复制 scripts/deploy.config.example.json 为 scripts/deploy.config.json 并修改其中参数。'); process.exit(1); } const config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8')); const USER = config.user; const IP = config.ip; // 服务器 IP const BASE_PATH = config.basePath; // 项目在服务器上的存放路径 const KEEP_RELEASES = config.keepReleases; // 服务器上保留的最近版本数 const SITE_HOST = config.siteHost; // 发版后健康检查域名 const LOCAL_DIST = path.resolve('dist'); const SSH_KEY = path.join(os.homedir(), '.ssh', config.sshKey); const SSH_OPTS = ['-i', SSH_KEY, '-o', 'StrictHostKeyChecking=no']; const HOST = `${USER}@${IP}`; const TARBALL = 'dist.tar.gz'; const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm'; const RELEASE_NAME = `v${timestamp()}_${process.pid}`; // 版本号(带 PID,避免并发/重复发布冲突) const REMOTE_RELEASE = `${BASE_PATH}/releases/${RELEASE_NAME}`; function timestamp() { const d = new Date(); const p = (n) => String(n).padStart(2, '0'); return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}_${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`; } function run(cmd, args, opts = {}) { const res = spawnSync(cmd, args, { stdio: 'inherit', ...opts }); if (res.error) { console.error(`❌ 无法执行命令 ${cmd}: ${res.error.message}`); if (res.error.code === 'ENOENT') { console.error( ' 请确认本机已安装对应命令(ssh/scp/tar)。Windows 10 1803+ 自带 OpenSSH 客户端与 tar。' ); } process.exit(1); } if (res.status !== 0) process.exit(res.status ?? 1); } console.log(`🚀 开始发布版本: ${RELEASE_NAME}`); try { // 1. 本地打包(失败立即中止,防止把坏产物发到线上) run(NPM, ['run', 'build']); // 2. 校验本地产物完整性 if (!existsSync(path.join(LOCAL_DIST, 'index.html')) || !existsSync(path.join(LOCAL_DIST, 'assets'))) { console.error('❌ 本地构建产物不完整(缺少 index.html 或 assets),中止发布'); process.exit(1); } // 3. 压缩并上传到独立的新版本目录(全程不触碰当前运行目录) run('tar', ['-czf', TARBALL, '-C', LOCAL_DIST, '.']); run('ssh', [...SSH_OPTS, HOST, `mkdir -p '${REMOTE_RELEASE}'`]); run('scp', [...SSH_OPTS, TARBALL, `${HOST}:${REMOTE_RELEASE}/${TARBALL}`]); // 4. 远程:解压 → 校验 → 补齐旧资源 → 原子切换 → 健康检查 → 清理 const remoteScript = readFileSync(path.join(__dirname, 'remote', 'deploy.sh'), 'utf8'); run( 'ssh', [ ...SSH_OPTS, HOST, `RELEASE='${REMOTE_RELEASE}' BASE='${BASE_PATH}' KEEP=${KEEP_RELEASES} HOST='${SITE_HOST}' bash -s`, ], { input: remoteScript, stdio: ['pipe', 'inherit', 'inherit'] } ); console.log(`✨ 发布成功!当前版本: ${RELEASE_NAME}`); } finally { // 无论成功失败都清理本地临时压缩包 rmSync(TARBALL, { force: true }); }