2012-06-07 142 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分支。没有办法确定哪一个是原始的。