311 lines
9.4 KiB
JavaScript
311 lines
9.4 KiB
JavaScript
#!/usr/bin/env node
|
|
import { select, input, confirm } from '@inquirer/prompts';
|
|
import ora from 'ora';
|
|
import { NodeSSH } from 'node-ssh';
|
|
import { exec } from 'child_process';
|
|
import { promisify } from 'util';
|
|
import path from 'path';
|
|
import { fileURLToPath } from 'url';
|
|
import dotenv from 'dotenv';
|
|
import chalk from 'chalk';
|
|
|
|
const execAsync = promisify(exec);
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
const rootDir = path.resolve(__dirname, '..');
|
|
|
|
// 加载环境变量
|
|
dotenv.config({ path: path.join(rootDir, '.env') });
|
|
|
|
// 服务器配置
|
|
const SERVER_CONFIG = {
|
|
host: process.env.DEPLOY_HOST,
|
|
username: process.env.DEPLOY_USER,
|
|
password: process.env.DEPLOY_PASSWORD,
|
|
deployPath: process.env.DEPLOY_PATH,
|
|
};
|
|
|
|
// 验证配置
|
|
const validateConfig = () => {
|
|
const required = ['DEPLOY_HOST', 'DEPLOY_USER', 'DEPLOY_PASSWORD', 'DEPLOY_PATH'];
|
|
const missing = required.filter(key => !process.env[key]);
|
|
|
|
if (missing.length > 0) {
|
|
console.error(chalk.red(`缺少环境变量: ${missing.join(', ')}`));
|
|
console.error(chalk.yellow('请检查 .env 文件配置'));
|
|
process.exit(1);
|
|
}
|
|
};
|
|
|
|
// 执行命令并返回输出
|
|
const runCommand = async (command, options = {}) => {
|
|
const { stdout } = await execAsync(command, {
|
|
cwd: rootDir,
|
|
maxBuffer: 1024 * 1024 * 10,
|
|
...options,
|
|
});
|
|
return stdout.trim();
|
|
};
|
|
|
|
// 获取指定分支的提交历史
|
|
const getCommitHistory = async (branch, limit = 15) => {
|
|
try {
|
|
// 先 fetch 确保有最新的远程分支引用
|
|
await runCommand(`git fetch origin ${branch}`).catch(() => {});
|
|
const output = await runCommand(
|
|
`git log origin/${branch} --pretty=format:"%h %s" -n ${limit}`
|
|
);
|
|
return output
|
|
.split('\n')
|
|
.filter(Boolean)
|
|
.map(line => {
|
|
const match = line.match(/^(\w+)\s{2}(.+)$/);
|
|
if (match) {
|
|
return { hash: match[1], message: match[2] };
|
|
}
|
|
return null;
|
|
})
|
|
.filter(Boolean);
|
|
} catch {
|
|
return [];
|
|
}
|
|
};
|
|
|
|
// 上传 dist 到服务器
|
|
const uploadDist = async (ssh, spinner) => {
|
|
spinner.start('设置目录权限...');
|
|
await ssh.execCommand(
|
|
`echo '${SERVER_CONFIG.password}' | sudo -S chown -R ${SERVER_CONFIG.username}:${SERVER_CONFIG.username} ${SERVER_CONFIG.deployPath}`
|
|
);
|
|
spinner.succeed('目录权限已设置');
|
|
|
|
spinner.start('清理远程 dist 目录...');
|
|
await ssh.execCommand(`rm -rf ${SERVER_CONFIG.deployPath}/dist`);
|
|
spinner.succeed('远程 dist 目录已清理');
|
|
|
|
spinner.start('上传 dist 文件夹...');
|
|
const distPath = path.join(rootDir, 'dist');
|
|
const remoteDistPath = `${SERVER_CONFIG.deployPath}/dist`;
|
|
|
|
let uploadedCount = 0;
|
|
const failed = [];
|
|
|
|
await ssh.putDirectory(distPath, remoteDistPath, {
|
|
recursive: true,
|
|
concurrency: 10,
|
|
tick: (localPath, remotePath, error) => {
|
|
if (error) {
|
|
failed.push(localPath);
|
|
} else {
|
|
uploadedCount++;
|
|
}
|
|
},
|
|
});
|
|
|
|
if (failed.length > 0) {
|
|
spinner.warn(`上传完成,${failed.length} 个文件失败`);
|
|
console.error(chalk.red('失败文件:', failed.join('\n')));
|
|
} else {
|
|
spinner.succeed(`上传完成,共 ${uploadedCount} 个文件`);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* 部署流程:
|
|
* 1. 提交当前分支的更改
|
|
* 2. 拉取目标分支(develop)最新代码,合并到当前分支
|
|
* 3. 构建项目
|
|
* 4. 上传到服务器
|
|
* 5. 把当前分支的代码同步推送到目标分支(develop),保证 develop 始终是最新的
|
|
*/
|
|
const deployLatest = async () => {
|
|
const spinner = ora();
|
|
const ssh = new NodeSSH();
|
|
const targetBranch = 'develop';
|
|
|
|
try {
|
|
// Step 1: 获取当前分支
|
|
spinner.start('获取当前分支...');
|
|
const currentBranch = await runCommand('git branch --show-current');
|
|
spinner.succeed(`当前分支: ${currentBranch}`);
|
|
|
|
// Step 2: 提交当前分支的更改
|
|
spinner.start('检查 Git 状态...');
|
|
const status = await runCommand('git status --porcelain');
|
|
spinner.succeed('Git 状态检查完成');
|
|
|
|
if (status) {
|
|
spinner.start('暂存所有更改...');
|
|
await runCommand('git add .');
|
|
spinner.succeed('文件已暂存');
|
|
|
|
const commitMessage = await input({
|
|
message: '请输入提交信息 (回车跳过使用默认):',
|
|
default: '修复bug',
|
|
});
|
|
|
|
spinner.start('提交更改...');
|
|
await runCommand(`git commit -m "feat: ${commitMessage}"`);
|
|
spinner.succeed(`已提交: feat: ${commitMessage}`);
|
|
} else {
|
|
console.log(chalk.gray('没有需要提交的更改'));
|
|
}
|
|
|
|
// Step 3: 拉取目标分支最新代码,合并到当前分支
|
|
spinner.start(`拉取远程 ${targetBranch} 分支最新代码...`);
|
|
try {
|
|
await runCommand(`git fetch origin ${targetBranch}`);
|
|
spinner.succeed(`已拉取 ${targetBranch} 最新代码`);
|
|
} catch {
|
|
spinner.warn(`远程 ${targetBranch} 分支不存在,跳过拉取`);
|
|
}
|
|
|
|
spinner.start(`合并 ${targetBranch} 到当前分支...`);
|
|
try {
|
|
await runCommand(`git merge origin/${targetBranch} --no-edit`);
|
|
spinner.succeed(`已合并 ${targetBranch} 到当前分支`);
|
|
} catch (mergeError) {
|
|
spinner.fail('合并时发生冲突');
|
|
console.error(chalk.red('\n请手动解决冲突后重试:'));
|
|
console.error(chalk.yellow('1. 查看冲突文件: git status'));
|
|
console.error(chalk.yellow('2. 手动解决冲突'));
|
|
console.error(chalk.yellow('3. git add <文件>'));
|
|
console.error(chalk.yellow('4. git commit'));
|
|
console.error(chalk.yellow('5. 重新运行部署命令\n'));
|
|
process.exit(1);
|
|
}
|
|
|
|
// Step 4: 推送当前分支
|
|
spinner.start(`推送当前分支 ${currentBranch}...`);
|
|
await runCommand(`git push origin ${currentBranch}`);
|
|
spinner.succeed(`已推送 ${currentBranch}`);
|
|
|
|
// Step 5: 构建
|
|
console.log(chalk.yellow('\n🚧 构建并发布中...\n'));
|
|
spinner.start('正在构建项目...');
|
|
await runCommand('npm run build:dev');
|
|
spinner.succeed('构建完成');
|
|
|
|
// Step 6: 上传到服务器
|
|
spinner.start('连接服务器...');
|
|
await ssh.connect({
|
|
host: SERVER_CONFIG.host,
|
|
username: SERVER_CONFIG.username,
|
|
password: SERVER_CONFIG.password,
|
|
});
|
|
spinner.succeed('服务器连接成功');
|
|
|
|
await uploadDist(ssh, spinner);
|
|
ssh.dispose();
|
|
|
|
// Step 7: 同步代码到目标分支,保证 develop 始终是最新的
|
|
if (currentBranch !== targetBranch) {
|
|
spinner.start(`同步代码到 ${targetBranch} 分支...`);
|
|
await runCommand(`git push origin ${currentBranch}:${targetBranch}`);
|
|
spinner.succeed(`已同步到 ${targetBranch} 分支`);
|
|
}
|
|
|
|
console.log(chalk.green('\n✅ 发布完成!\n'));
|
|
console.log(chalk.cyan('访问地址: https://dev-momatch.robotquan.com'));
|
|
console.log(chalk.gray(`当前分支: ${currentBranch} → 已同步到 ${targetBranch}\n`));
|
|
} catch (error) {
|
|
spinner.fail('操作失败');
|
|
console.error(chalk.red(error.message));
|
|
ssh.dispose();
|
|
process.exit(1);
|
|
}
|
|
};
|
|
|
|
// 回滚到历史版本
|
|
const rollback = async () => {
|
|
const spinner = ora();
|
|
const ssh = new NodeSSH();
|
|
const targetBranch = 'develop';
|
|
|
|
try {
|
|
spinner.start('获取版本历史...');
|
|
const commits = await getCommitHistory(targetBranch, 15);
|
|
spinner.stop();
|
|
|
|
if (commits.length === 0) {
|
|
console.log(chalk.yellow('未找到提交历史'));
|
|
return;
|
|
}
|
|
|
|
const selected = await select({
|
|
message: '请选择要回滚的版本:',
|
|
choices: commits.map(c => ({
|
|
name: `${chalk.cyan(c.hash)} ${c.message}`,
|
|
value: c.hash,
|
|
})),
|
|
});
|
|
|
|
const confirmed = await confirm({
|
|
message: `确定要回滚到版本 ${selected} 吗?`,
|
|
default: false,
|
|
});
|
|
|
|
if (!confirmed) {
|
|
console.log(chalk.gray('已取消'));
|
|
return;
|
|
}
|
|
|
|
const currentBranch = await runCommand('git branch --show-current');
|
|
|
|
spinner.start(`检出版本 ${selected}...`);
|
|
await runCommand(`git checkout ${selected}`);
|
|
spinner.succeed(`已检出版本 ${selected}`);
|
|
|
|
console.log(chalk.yellow('\n🚧 构建并发布中...\n'));
|
|
spinner.start('正在构建项目...');
|
|
await runCommand('npm run build:dev');
|
|
spinner.succeed('构建完成');
|
|
|
|
spinner.start('连接服务器...');
|
|
await ssh.connect({
|
|
host: SERVER_CONFIG.host,
|
|
username: SERVER_CONFIG.username,
|
|
password: SERVER_CONFIG.password,
|
|
});
|
|
spinner.succeed('服务器连接成功');
|
|
|
|
await uploadDist(ssh, spinner);
|
|
ssh.dispose();
|
|
|
|
spinner.start(`返回 ${currentBranch || targetBranch} 分支...`);
|
|
await runCommand(`git checkout ${currentBranch || targetBranch}`);
|
|
spinner.succeed(`已返回 ${currentBranch || targetBranch} 分支`);
|
|
|
|
console.log(chalk.green('\n✅ 回滚完成!\n'));
|
|
console.log(chalk.cyan(`已回滚到版本: ${selected}`));
|
|
} catch (error) {
|
|
spinner.fail('操作失败');
|
|
console.error(chalk.red(error.message));
|
|
ssh.dispose();
|
|
process.exit(1);
|
|
}
|
|
};
|
|
|
|
// 主函数
|
|
const main = async () => {
|
|
console.log(chalk.bold.blue('\n🚀 robo-forge DEV 部署工具\n'));
|
|
console.log(chalk.gray('目标分支: develop | 部署环境: dev\n'));
|
|
|
|
validateConfig();
|
|
|
|
const action = await select({
|
|
message: '请选择操作:',
|
|
choices: [
|
|
{ name: '📦 部署最新代码', value: 'deploy' },
|
|
{ name: '⏪ 回滚到历史版本', value: 'rollback' },
|
|
],
|
|
});
|
|
|
|
if (action === 'deploy') {
|
|
await deployLatest();
|
|
} else {
|
|
await rollback();
|
|
}
|
|
};
|
|
|
|
main().catch(console.error);
|