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

Dzi*_*mid 6 git

可能重复:
查找分支的父分支

如何找出有问题的分支(如果有)分离的git分支的名称?

Sha*_*baz 5

我们很容易认为master永远是master永远my_branchmy_branch但事实并非如此。假设您的存储库位于 Github、Windows、Linux 和 Office 中。

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

github/master
github/my_branch
windows/master
windows/my_branch
linux/master
linux/my_branch
office/master
office/my_branch
Run Code Online (Sandbox Code Playgroud)

master作为一个人,你将它们视为my_branch8 个不同的分支,但 git 将它们视为 8 个不同的分支。因此,如果您有这样的网络:

------------------------------------------------ linux/master
 \--/ \-------/      /            \-------- office/my_branch
  | \---|--\--------/-------------------\------- my_branch
  |     |
  |   office/master
  | 
windows/master
Run Code Online (Sandbox Code Playgroud)

问从何my_branch而来是什么意思?这是许多分支合并的结果!


所以我想告诉你的是,你的问题有一个哲学问题。然而,有一种方法可以回答这个问题,尽管并不完美。首先我们看一下git log

git log my_branch --pretty=oneline --graph
Run Code Online (Sandbox Code Playgroud)

为您提供了合并等内容的精彩演示。从 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.
Run Code Online (Sandbox Code Playgroud)

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

git log my_branch --pretty=format:"%H" --first-parent
Run Code Online (Sandbox Code Playgroud)

使用以下命令,您可以知道哪些分支包含 SHA1:

git branch --contains <commit>
Run Code Online (Sandbox Code Playgroud)

使用这些命令将脚本放在一起,您可以使用以下脚本,该脚本基本上可以找到包含在您感兴趣的分支之外的另一个分支中的最新 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"
Run Code Online (Sandbox Code Playgroud)

我说不完美,是因为下面的情况。想象一下 ifmy_branch是从 分支出来的master。事实上,您会看到这样的图表:

                    /------------ master
------(master)-----
                    \------------ my_branch
Run Code Online (Sandbox Code Playgroud)

初始提交包含在两个分支的历史记录中。不知道它们最初是从师父那里来的。因此,该脚本将告诉您 是my_branch从 分支的master,同时告诉您master是从 分支的my_branch。没有办法分辨哪一个是原来的。