如何一键删除所有分支?

157 阅读1分钟

有没有因为本地分支过多,不想手动删除而心烦?

试试如下脚本吧,保留你想要的分支,其它一键删除。

/**
 * @title 删除本地多余分支
 * @description 删除除当前分支和输入分支以外的其它分支
 * @example:
 *  当前分支: test
 *  终端执行:node ./filter-branch.js master dev
 *  结果:本地分支仅保留 test、master、dev,其它全部删除
*/
const fs = require('fs');
const readline = require('readline');
const { exec } = require('child_process');
const stableBranchs = process.argv.splice(2);

exec('git symbolic-ref --short -q HEAD >/tmp/current-branch.log');
const currentBranch = fs.readFileSync('/tmp/current-branch.log', 'utf-8')
  .split('\n')
  .filter(item => !item);

stableBranchs.push(currentBranch);

exec(`git branch >/tmp/branchs.log`);
const branchs = fs.readFileSync('/tmp/branchs.log', 'utf-8')
  .split('\n')
  .map(item => item.replace(/\s+/g, ''))
  .filter(item => item && !stableBranchs.includes(item) && !item.startsWith('*'));

const pipeline =readline.createInterface({
  input: process.stdin,
  output: process.stdout
})

// 最终删除的 branchs
console.log(branchs);
pipeline.question(`确定删除以上分支吗(y/n)?`, check => {
  if (['y', 'Y'].includes(check)) { 
    branchs.forEach(branch => { 
      exec(`git branch -D ${branch}`);
    })
    console.log(`删除完成`)
  }
  pipeline.close()
})

step1: 根目录新建 filter-branch.js 文件,复制如上代码到里面,可能会有 node 版差异。当然,文件名和目录可以随意

step2: 终端执行 node ./filter-branch.js master 1.2.xmaster1.2.x 为想要保留的分支

image.png