这个分支从哪个git分支检出?

时间:2012-06-07 12:31:52

标签: git

  

可能重复:
  Find the parent branch of a branch

如何找出有问题的分支从哪个分支的git分支的名称(如果有的话)?

1 个答案:

答案 0 :(得分:3)

我们很容易认为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.

使用它,您可以获得分支的线性历史记录。删除图表并仅输出SHA1,您将获得:

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_branch是否从master分支出来。事实上,你会看到如下图:

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

初始提交包含在两个分支的历史记录中。不知道他们最初来自大师。因此,此脚本会告诉您my_branch已从master分支,同时告诉您master已从my_branch分支。没有办法说出哪一个是原始的。

相关问题