#!/usr/bin/env node /** * 跨平台回滚脚本(Windows / macOS / Linux 通用) * * 等价于原 rollback.sh,改用 Node.js 实现,使 Windows 开发环境无需安装 sh/bash。 * 依赖本机已安装:ssh(Windows 10 1803+ 自带 OpenSSH 客户端)。 * * 用法:npm run rollback */ import { spawnSync } from 'node:child_process'; import { existsSync, readFileSync } 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 SSH_KEY = path.join(os.homedir(), '.ssh', config.sshKey); const SSH_OPTS = ['-i', SSH_KEY, '-o', 'StrictHostKeyChecking=no']; const HOST = `${USER}@${IP}`; console.log('⏪ 正在回滚到上一个版本...'); const remoteScript = readFileSync(path.join(__dirname, 'remote', 'rollback.sh'), 'utf8'); const res = spawnSync( 'ssh', [...SSH_OPTS, HOST, `BASE='${BASE_PATH}' bash -s`], { input: remoteScript, stdio: ['pipe', 'inherit', 'inherit'] } ); if (res.error) { console.error(`❌ 无法执行 ssh: ${res.error.message}`); if (res.error.code === 'ENOENT') { console.error(' 请确认本机已安装 OpenSSH 客户端(Windows 10 1803+ 自带)。'); } process.exit(1); } process.exit(res.status ?? 1);