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

例子:

分支机构(本地和远程)

主人原始/主起源/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。


当前回答

下面是一个简单的答案,我使用git客户机得到了这个答案:

从计算机中完全删除存储库,然后再次签出。

不要玩弄风险脚本。

其他回答

根据以上信息,这对我来说很有效:

git br -d `git br -vv | grep ': gone] ' | awk '{print $1}' | xargs`

它将删除远程上所有带有“:gone]”的本地分支。

也许这个命令就是你想要的。

运行后:

git remote prune origin

然后运行:

diff <(git branch | sed -e 's/*/ /g') <(git branch -r | sed -e 's/origin\///g') | grep '^<'

这将显示所有不在(gitbranch-r)而是在(git branch)中的分支

此方法有一个问题,它还将在本地显示以前未推送的分支

我不确定要用多久,但我现在确实使用git-up,这可以解决这个问题。

我做了git,它开始跟踪新的分支并删除旧的分支。

为了清楚起见,这不是现成的git命令-https://github.com/aanand/git-up

顺便说一句,它还藏着脏树,只需把它捡起来就可以重新放回原处。

希望对某人有用

因为有些答案不能防止意外删除

git fetch-p&&LANG=c git branch-vv|awk'/:gone]/&&/^\*/{print$1}‘|xargs git branch-d

过滤掉第一列中有*的分支是很重要的。

我已经用GitPython编写了一个Python脚本来删除远程不存在的本地分支。

    import git
    import subprocess
    from git.exc import GitCommandError
    import os

    def delete_merged_branches():
        current_dir = input("Enter repository directory:")
        repo = git.Repo(current_dir)
        git_command = git.Git(current_dir)

        # fetch the remote with prune, this will delete the remote references in local.
        for remote in repo.remotes:
            remote.fetch(prune=True)
        
        local_branches = [branch.name for branch in repo.branches]
        deleted_branches = []

        # deleted_branches are the branches which are deleted on remote but exists on local.
        for branch in local_branches:
            try:
                remote_name = 'origin/'+ branch
                repo.git.checkout(remote_name)
            except GitCommandError:
            # if the remote reference is not present, it means the branch is deleted on remote.
                deleted_branches.append(branch)
            
        for branch in deleted_branches:
            print("Deleting branch:"+branch)
            git_command.execute(["git", "branch", "-D",branch])

    
        # clean up the work flow.
        repo.git.checkout('master')
        repo.git.pull()

    if __name__ == '__main__':
        delete_merged_branches()

希望有人觉得它有用,如果我错过了什么,请添加评论。