![](/img/trans.png)
[英]How do I automatically delete all the github generated patch branches from a fork
[英]Delete all branches that are no longer on Github
我在GitHub上有Branch-Master,Branch-A,Branch-B,Branch-C分支。 我通常合並為master並刪除合並的分支。 這在我的本地機器上留下了一堆分支,但不是GitHub。
如何自動自動刪除本地分支? 我想創建一個git鈎子來做到這一點。
當我嘗試
git remote prune origin
然后運行git branch,我仍然看到我的所有分支,甚至是那些合並並刪除到master中的分支。
我知道我能做到
git branch -d {the_local_branch}
手動,但這在做githook或我有多個分支系統刪除時沒有幫助。
我不喜歡這里給出的答案: 如何刪除已合並的所有Git分支?
它們是基於名稱,並推斷已刪除的分支,而不是以某種方式顯式傳遞特定於該分支的分支ID。 我在提供的鏈接中理解的是,如果我創建一個與已刪除分支相同的分支名稱,它也將被刪除,即使它們是不同的分支。
不解決我的詢問,因為它的解決方案已在上面說明。
如果它們存在,我寧願使用分支uid的某種類型的比較函數。
您可以通過一個命令一次性刪除所有分支(除了已簽出的分支):
git branch --list | xargs git branch -D
如果要指定某個模式以匹配分支名稱,您也可以這樣做:
git branch --list k* | xargs git branch -D
並借助於
git remote prune origin
您可以刪除系統中不再引用的遠程分支。
希望這可以幫助 !
正如phd在評論中指出的那樣,分支機構沒有基礎ID 。 分支名稱就是在你的倉庫,你或你的請求創建一個本地名稱,標識一個具體的承諾。 您可以隨時更改此名稱,只要它符合分支名稱的要求即可更改為您喜歡的任何字符串。 Git不會記得曾經有過其他名字。
現在,還有一些額外的信息:你的.git/config
文件可以,並且通常會在其中,每個分支,一些注釋,如:
[branch "master"]
remote = origin
merge = master
[branch "develop"]
remote = another-remote
merge = develop
這些設置定義分支的上游設置 。 一個分支根本沒有上游 - 在這種情況下,兩個設置不存在 - 或者一個上游,在這種情況下,兩個設置存在並描述上游,使用舊的歷史方法處理此前的兩個部分發明了遠程跟蹤名稱。
如果使用標准Git命令重命名分支,則會自動重命名這些配置節。 例如,在git branch -m develop xyz
,你將擁有:
[branch "xyz"]
remote = another-remote
merge = develop
這意味着你的本地分支xyz
的上游是another-remote/develop
。 (這假定標准fetch =
遠程another-remote
。)
通過一些努力,可以讀取每個分支的上游設置(如果有的話):使用git for-each-ref
枚舉所有分支,然后,對於每個分支,使用git rev-parse --symbolic-full-name <branch>@{upstream}
查看它是否有上游,如果是,上游名稱是什么。 請注意,您必須要小心,因為“遠程”可以設置為.
,表明某個本地分支的上游是另一個本地分支。
結合這種方案測試的(“確實分支X具有上游,並且如果是這樣,它實際上是一個遠程跟蹤名稱,和什么遠程跟蹤名字是什么?”)與第二測試(“用后git remote <remote> prune
或git fetch <remote> --prune
,遠程跟蹤名稱是否存在?“)可以得到你想要的。 你需要做一些編碼(例如bash腳本)。 使其最優化,或者在鈎子內工作很難,但總體任務非常簡單:
git for-each-ref --format='%(refname:short)' refs/heads |
while read branch; do
# make sure it has an upstream set -- if not, ignore
upstream=$(git rev-parse --symbolic-full-name ${branch}@{upstream}) || continue
# make sure the upstream is a remote-tracking name
case $upstream in
refs/remotes/*) ;;
*) continue;;
esac
# get the name of the remote
remote=${upstream#refs/remotes/}
remote=${remote%%/*}
# prune remote-tracking branches
git remote $remote prune
# and test whether the upstream still exists
git rev-parse $upstream && continue
# $branch has upstream $upstream which is gone, so:
echo git branch -D $branch
done
這是非常未經測試的,並且缺少重要的部分,例如保持它不會刪除的分支(每個rev-parse
將向stdout和/或stderr發送消息)。 它實際上也沒有刪除任何分支:因為它可能是相當不可恢復的,所以人們首先需要徹底測試它,然后才刪除echo
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.