是否有一种简单的方法可以删除所有远程对等分支不再存在的跟踪分支?

例子:

分支机构(本地和远程)

主人原始/主起源/bug-fix-a起源/bug-fix-b起源/bug-fix-c

在本地,我只有一个主分支。现在我需要处理bug-fix-a,所以我检查它,处理它,并将更改推到远程。接下来,我对bug-fix-b做同样的操作。

分支机构(本地和远程)

主人bug-fix-abug-fix-b型原始/主起源/bug-fix-a起源/bug-fix-b起源/bug-fix-c

现在我有本地分支机构master,bug-fix-a,bug--fix-b。主分支维护者将把我的更改合并到主分支中,并删除他已经合并的所有分支。

因此,当前状态为:

分支机构(本地和远程)

主人bug-fix-abug-fix-b型原始/主起源/bug-fix-c

现在我想调用一些命令来删除分支(在本例中为bug-fix-a、bug-fix-b),这些分支在远程存储库中不再表示。

它类似于现有命令git remote prune origin,但更类似于git local prune origin。


当前回答

看来每个人都有解决办法。好吧,如果你喜欢一个带有TUI(基于文本的用户界面)的交互式工具,我写了一个叫做gitxcleaner的工具。它可以找到合并的分支、重新基础的分支(使用相同的提交消息提交)、修剪的分支或手动选择的分支。

https://github.com/lzap/git-xcleaner

其他回答

我使用了一个简短的方法来完成这项任务,我建议你也这样做,因为这样可以节省一些时间,并提高你的可见度

只需将以下代码段添加到.bashrc(macos上的.bashprofile)中。

git-cleaner() { git fetch --all --prune && git branch --merged | grep -v -E "\bmaster|preprod|dmz\b" | xargs -n 1 git branch -d ;};

获取所有遥控器仅从git中获取合并的分支从此列表中删除“受保护/重要”分支删除其余部分(例如,清理和合并的分支)

您必须编辑grep正则表达式以满足您的需要(这里,它防止删除master、prepod和dmz)

我发现基于Powershell的解决方案比这里的许多实现更清晰。

# prune deleted remoted branches
git fetch -p

# get all branches and their corresponding remote status
# deleted remotes will be marked [gone]
git branch -v |
  #find ones marked [gone], capture branchName
  select-string -Pattern '^  (?<branchName>\S+)\s+\w+ \[gone\]' | 
  foreach-object{ 
     #delete the captured branchname.
     git branch -D $_.Matches[0].Groups['branchName']
  }

对于Windows或其他不想/不会编写命令行脚本或不想使用PowerShell的人来说,这是一个更简单的解决方案。

将分支列表转储到文件中gitbranch>branches.txt(或git branch--merged>branches.txt,如果您是腰带和吊带类型;gitbranch-d将防止删除未合并的分支)

在编辑器中打开该文件并合并所有行(我使用了升华文本,所以突出显示所有行并按ctrl+j)

在分支列表前面添加gitbranch-d。

全选、复制并粘贴(在windows cmd窗口中单击鼠标右键)到命令行中。

git remote prune origin
git branch -d bug-fix-a bug-fix-b

使用脚本执行此操作的风险在此处解决:https://stackoverflow.com/a/47939403/4592031

这里有一个解决方法,我用它来处理鱼壳。在Mac OS X 10.11.5、fish 2.3.0和git 2.8.3上测试。

function git_clean_branches
  set base_branch develop

  # work from our base branch
  git checkout $base_branch

  # remove local tracking branches where the remote branch is gone
  git fetch -p

  # find all local branches that have been merged into the base branch
  # and delete any without a corresponding remote branch
  set local
  for f in (git branch --merged $base_branch | grep -v "\(master\|$base_branch\|\*\)" | awk '/\s*\w*\s*/ {print $1}')
    set local $local $f
  end

  set remote
  for f in (git branch -r | xargs basename)
    set remote $remote $f
  end

  for f in $local
    echo $remote | grep --quiet "\s$f\s"
    if [ $status -gt 0 ]
      git branch -d $f
    end
  end
end

几点注意事项

确保设置正确的base_branch。在本例中,我使用develop作为基本分支,但它可以是任何东西。

这一部分非常重要:grep-v“\(master\|$base_branch\|\*\)”。它确保您不会删除主分支或基本分支。

我使用gitbranch-d<branch>作为额外的预防措施,以便不删除任何尚未与上游或当前HEAD完全合并的分支。

一种简单的测试方法是用echo“将删除$f”替换gitbranch-d$f。

我想我还应该补充一句:使用风险自负!