使用git远程修剪原点,我可以删除不在远程上的本地分支。

但是我还想删除从这些远程分支创建的本地分支(检查它们是否未合并会很好)。

我该怎么做呢?


当前回答

可以配置Git在获取时自动删除对已删除的远程分支的引用:

git config --global fetch.prune true

当调用git fetch或git pull之后,对已删除的远程分支的引用将自动删除。

其他回答

我很确定git remote prune origin是你想要的。

你可以运行它作为git远程剪枝起源-演练,看看它会做什么不做任何改变。

以下是@wisbucky对Windows用户的回答:

for /f "tokens=1" %i in ('git branch -vv ^| findstr ": gone]"') DO git branch %i -d

我使用posh-git,不幸的是PS不喜欢裸体for,所以我创建了一个普通的'ol命令脚本,名为PruneOrphanBranches.cmd:

@ECHO OFF
for /f "tokens=1" %%i in ('git branch -vv ^| findstr ": gone]"') DO CALL :ProcessBranch %%i %1

GOTO :EOF

:ProcessBranch
IF /I "%2%"=="-d" (
    git branch %1 %2
) ELSE (
    CALL :OutputMessage %1
)
GOTO :EOF

:OutputMessage
ECHO Will delete branch [%1] 
GOTO :EOF

:EOF

不带参数调用它以查看列表,然后用“-d”调用它来执行实际的删除或对任何没有完全合并但无论如何都想删除的分支执行“-d”。

删除远程分支:

$git remote prune origin

删除已合并的本地分支。

$git branch -D $(git branch --merged)

我已经把公认的答案变成了一个健壮的脚本。您可以在我的git-extensions存储库中找到它。

$ git-rprune --help
Remove old local branches that do not exist in REMOTE any more.
With --test, only print which local branches would be deleted.
Note: To do this automatically on each fetch / pull:
    git config --global fetch.prune true
Usage: git-rprune REMOTE [-t|--test|-f|--force] [-?|-h|--help]

除了Schleis的答案(它工作得很完美),它还可以集成到Visual Studio中,所以在VS中打开git repo时修剪本地分支非常简单。

您可以使用外部工具功能调用sh.exe (git bash)与特定的目录和命令。它位于工具>外部工具菜单选项中(在VS 2022 17.1.0中)。我使用的参数如下:

命令:{Path-To-Git-Installation-Location} \ bin \ sh.exe

参数:——cd=$(SolutionDir) -c "git fetch -p;Git branch -r | awk '{print $1}' | egrep -v -f /dev/ fg /0 <(Git branch -vv | grep origin) | awk '{print $1}' | xargs Git branch -d"

初始目录:$(SolutionDir)

Git修剪本地分支的截图

值得注意的是,只有当你在VS中打开的解决方案在git repo目录中时,这才会起作用。

最后提醒-这可以通过Visual Studio的按键绑定用户界面在设置>通用>键盘和搜索工具进行按键绑定。ExternalCommand[n],其中n是外部命令表中的位置,您有这个外部工具的位置(它们可以在工具>外部工具对话框中重新排序)。请看下面的截图。

键盘绑定外部工具命令