使用node.js 写脚本,控制git 半自动将当前分支合并到dev分支
const inquirer = require('inquirer');
const exec = require('child_process').exec;
const execSync = require('child_process').execSync;
const fs = require('fs');
const commit = execSync('git show -s --format=%H').toString().trim();
const branch = execSync('git rev-parse --abbrev-ref HEAD').toString().trim();
const ora = require('ora');
const loading = ora('加载中');
inquirer
.prompt([
{
type: 'list',
name: 'start',
message: '该脚本将会把当前分支合并到dev上,要合并到dev吗?',
choices: [
{ key: '1', name: '是的,并且我确定当前是feature分支', value: true },
{ key: '2', name: '不了', value: false },
],
},
])
.then((res) => {
if (res.start) {
startMergeDev();
} else {
console.info('一切都结束了!!!');
}
});
async function startMergeDev() {
const operation_1 = () => {
console.info('\x1B[32m%s\x1b[0m', '第一步:切换分支到dev');
const text = execSync('git checkout dev').toString().trim();
console.info(['1-完成:', text].join('\n'));
};
const operation_2 = async () => {
console.info('\x1B[32m%s\x1b[0m', '第二步:拉取远程更新');
loading.start();
try {
text = execSync('git pull').toString().trim();
loading.succeed('2-完成');
console.info([text].join('\n'));
} catch (error) {
loading.fail('2-拉取远程更新失败');
console.info([error].join('\n'));
const res = await inquirer.prompt([
{
type: 'list',
name: 'val',
message: '远程更新失败, 是否重新请求一次?',
choices: [
{ key: '1', name: '好的', value: true },
{ key: '2', name: '不了,我要退出', value: false },
],
},
]);
if (!res.val) {
process.exit();
} else {
await operation_2();
}
}
};
const operation_3 = async () => {
console.info('\x1B[32m%s\x1b[0m', '第三步:合并分支');
try {
const text = execSync('git checkout dev').toString().trim();
console.info(['3-完成:', text].join('\n'));
} catch (error) {
console.info(['3-合并分支失败:', error].join('\n'));
const res = await inquirer.prompt([
{
type: 'list',
name: 'val',
message: '合并分支失败, 请先解决再决定是否继续?',
choices: [
{ key: '1', name: '继续', value: true },
{ key: '2', name: '不了,我要退出', value: false },
],
},
]);
if (!res.val) {
process.exit();
} else {
await operation_3();
}
}
};
const operation_4 = () => {
console.info('\x1B[32m%s\x1b[0m', '第四步:推送代码到远程dev');
text = execSync(`git push origin dev`).toString().trim();
console.info(['4-完成:', text].join('\n'));
};
const operation_5 = () => {
console.info('\x1B[32m%s\x1b[0m', '第五步:回到当前分支');
text = execSync(`git checkout ${branch}`).toString().trim();
console.info([text].join('\n'));
};
if (branch == 'dev' || branch.indexOf('dev') != -1) {
console.info('\x1B[33m%s\x1b[0m', '当前就是dev分支好不好!?');
} else if (branch.indexOf('feature') != -1) {
await operation_1();
await operation_2();
await operation_3();
await operation_4();
await operation_5();
} else {
console.info('当前分支:' + branch);
console.info('\x1B[33m%s\x1b[0m', '请先切换到featrue分支,再进行操作!');
}
}