2012-06-07 140 views
5

可能重複:
Find the parent branch of a branch哪個git分支是從這個分支檢出的?

我如何找出的Git分支有關的分支從分裂(如果有的話)的名字?

+0

您的意思是它正在跟蹤的遠程分支,或分支分支分支(如果有的話)?我不認爲你總能找到後者。 –

+0

這個分支(如果有的話)的本地分支。無法說明這一點比你做得更好。 – Dziamid

+0

我不認爲Git甚至記錄了這些信息,儘管我可能會誤解。 –

回答

2

我們很容易認爲master總是mastermy_branch總是my_branch,但事實並非如此。假設你在Github,你的windows,你的linux和你的辦公室有你的倉庫。

你因此有8個不同的分支:

github/master 
github/my_branch 
windows/master 
windows/my_branch 
linux/master 
linux/my_branch 
office/master 
office/my_branch 

你作爲一個人看到他們爲mastermy_branch但Git把它們作爲8個不同的分支。所以,如果你有這樣一個網絡:

------------------------------------------------ linux/master 
\--/ \-------/ /   \-------- office/my_branch 
    | \---|--\--------/-------------------\------- my_branch 
    |  | 
    | office/master 
    | 
windows/master 

是什麼意思了問my_branch從何而來?這是許多分支合併的結果!


在那裏,所以我想告訴你的是,有一個哲學問題,你的問題。然而,有一種方法可以回答它,儘管並不完美。首先讓我們來看看git log

git log my_branch --pretty=oneline --graph 

爲您提供了合併和東西的一個漂亮的演示。從git-log手冊頁:

--first-parent 
    Follow only the first parent commit upon seeing a merge commit. This option can give a better overview when viewing the evolution of a particular topic branch, 
    because merges into a topic branch tend to be only about adjusting to updated upstream from time to time, and this option allows you to ignore the individual 
    commits brought in to your history by such a merge. 

使用它可以得到分支的線性歷史記錄。卸下圖形和輸出只有SHA1s,您將獲得:

git log my_branch --pretty=format:"%H" --first-parent 

使用下面的命令,你可以知道哪些分支包含一個SHA1:

git branch --contains <commit> 

把腳本一起使用這些命令,你可以使用以下腳本,該腳本基本上可以找到另一個分支中包含的最新SHA1,而不是您感興趣的分支。然後輸出該分支。 (注:我不擅長在bash腳本還,所以這可能不是那麼有效):

#! /bin/bash 

if [ $# -lt 1 ]; then 
    branch=master 
else 
    branch=$1 
fi 

sha1s=$(git log $1 --pretty=format:"%H") 
res="Doesn't branch from anything" 

for i in $sha1s; do 
    b=$(git branch --contains $i | awk '{ if (NF > 1) print $2; else print $1 }') # use awk to remove * from current branch 
    other_branch=""; 
    for j in $b; do 
    if [ $branch != $j ]; then 
     other_branch=$j 
     break; 
    fi 
    done 
    if [ -n "$other_branch" ]; then 
    res=$other_branch 
    break 
    fi 
done 

printf -- '%s\n' "$res" 

我說這不是完美的,因爲下面的情況。想象一下,如果my_branchmaster分支出來。事實上,你再看到這樣的圖形:

    /------------ master 
------(master)----- 
        \------------ my_branch 

最初提交的含量爲分支的歷史。不知道他們最初來自主人。因此,該腳本會告訴您my_branchmaster分支,同時告訴您mastermy_branch分支。沒有辦法確定哪一個是原始的。