使用node把git当前代码分支的本地代码保存到暂存区
使用node的child_process模块中的spawnSync同步执行命令
const { spawnSync } = require('child_process');
使用spawnSync方法获取当前git状态,因为js文件在项目外所以添加cwd控制命令执行路径为项目根目录
const { stdout, status } = spawnSync('git', ['status', '-s'], { cwd: './your-project' });
判断获取的git状态和命令执行状态,有未add的文件就执行add操作
if (stdout.toString().length > 0 && status === 0) {
if (status === 0) {
const { stdout, status } = spawnSync('git', ['add', '.'], { cwd: './your-project' });
} else {
console.log('添加文件到暂存区失败');
process.exit(1);
}
}
最后使用readline询问暂存备注并保存
const readline = require('readline');
(function () {
const { stdout, status } = spawnSync('git', ['status', '--porcelain'], { cwd: './your-project' });
if (stdout.toString().length > 0 && status === 0) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('请输入您的本地缓存的备注: ', (name) => {
const { stdout, status } = spawnSync('git', ['stash', 'save', '-m', name], { cwd: './your-project' });
if (status === 0) {
console.log(stdout.toString());
rl.close();
}
rl.close();
});
} else {
console.log('没有本地代码需要缓存');
}
})
全部代码如下:
const { spawnSync } = require('child_process');
const readline = require('readline');
const { stdout, status } = spawnSync('git', ['status', '-s'], { cwd: './your-project' });
if (stdout.toString().length > 0 && status === 0) {
if (status === 0) {
const { stdout, status } = spawnSync('git', ['add', '.'], { cwd: './your-project' });
} else {
console.log('添加文件到暂存区失败');
process.exit(1);
}
}
(function () {
const { stdout, status } = spawnSync('git', ['status', '--porcelain'], { cwd: './your-project' });
if (stdout.toString().length > 0 && status === 0) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('请输入您的本地缓存的备注: ', (name) => {
const { stdout, status } = spawnSync('git', ['stash', 'save', '-m', name], { cwd: './your-project' });
if (status === 0) {
console.log(stdout.toString());
rl.close();
}
rl.close();
});
} else {
console.log('没有本地代码需要缓存');
}
})

浙公网安备 33010602011771号