node实现自动部署
环境准备
# 安装依赖 版本号最好一致
"chalk": "^4.1.2",
"child_process": "^1.0.2",
目录
src/config
init.js [用于初始化执行,获取当前操作的分支]
publish.js [发布所需核心命令]
代码
/* init.js */
/* 开发分支直接发布脚本 npm run daily */
const { exec, spawn } = require('child_process');
const chalk = require('chalk');
exec('git rev-parse --abbrev-ref HEAD', (error, stdout, stderr) => {
if (error) {
console.error(`获取当前分支名出错: ${error}`);
return;
}
if (stderr) {
console.error(`取当前分支名输出错误: ${stderr}`);
return;
}
// 使用当前分支名作为参数调用publish.js
const currentBranch = stdout.trim();
console.log(chalk.bgYellowBright(`当前开发分支是: ${currentBranch}`));
const publishScript = spawn('node', ['config/publish.js', currentBranch]);
publishScript.stdout.on('data', (data) => {
console.log(chalk.greenBright(`日志:`, chalk.yellowBright(data)));
});
publishScript.stderr.on('data', (data) => {
console.error(chalk.redBright(`错误日志: ${data}`));
});
publishScript.on('close', (code) => {
console.log(chalk.yellowBright(`进程结束 ${code}`));
});
});
/* publish.js */
const { exec } = require('child_process');
const branchName = process.argv[2]; // 获取命令行传入的分支名
if (!branchName) {
console.error('Please provide the branch name as an argument.');
process.exit(1);
}
/* 日常环境分支 */
const daily_branch = 'daily/0.0.999';
/* 线上环境分支 */
const prod_branch = 'master';
/* 当前操作分支 */
const current_branch = prod_branch;
// 定义需要执行的Git命令
const commands = [
// 提交代码
`npm run commit`,
// 切换到daily分支
`git checkout ${current_branch}`,
// 拉取最新代码,确保本地分支是最新的
`git pull origin ${current_branch}`,
// 合并开发分支到daily分支
`git merge ${branchName} --no-ff -m "Merge ${branchName} into ${current_branch}"`,
// 推送到远程daily分支
`git push origin ${current_branch}`,
// 执行发布命令,假设这里目前执行的是 代码格式化命令到时候可替换
`npm run formate`,
// 切换回开发分支
`git checkout ${branchName}`
];
/* 取消提交代码时报的错 */
const ignore_error = ['npm run commit'];
// 顺序执行Git命令
function executeCommands(index = 0) {
if (index === commands.length) {
console.log(`发布完成✅`);
return;
}
const command = commands[index];
console.log(`准备执行第${index + 1}个命令: ${command}`);
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`错误的命令: ${command}`);
if (ignore_error.indexOf(command) === -1) {
console.error(`错误的输出: ${stderr}`);
console.error(`错误日志: ${error}`);
process.exit(1);
} else {
console.log(`已忽略`);
}
}
console.log(`准第${index + 1}个命令执行完成
标签:node,const,log,部署,自动,branch,error,console,分支
From: https://www.cnblogs.com/gjzsa/p/18429718