git - 这个分支是从哪个 git 分支 checkout 的?

标签 git

<分区>

Possible Duplicate:
Find the parent branch of a branch

如何找出相关分支从中分离出来的 git 分支的名称(如果有)?

最佳答案

我们很容易认为 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 来自哪里是什么意思?它是许多分支 merge 的结果!


那么,我想告诉你的是,你的问题存在一个哲学问题。然而,有一种方法可以回答它,尽管不是很完美。首先让我们看一下git log:

git log my_branch --pretty=oneline --graph

很好地介绍了 merge 和内容。来自 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_branchmaster 分支出来。事实上,您会看到这样的图表:

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

初始提交包含在两个 分支的历史记录中。不知其原出自师父。因此,这个脚本会告诉你 my_branch 是从 master 分支出来的,同时告诉你 master 是从 my_branch 分支出来的。无法分辨哪一个是原始的。

关于git - 这个分支是从哪个 git 分支 checkout 的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10931845/

相关文章:

多项目团队的 Git 组织

git - 使用 git-p4 获取整个文件的历史记录

git:推送更改特别是提交

git - 如何处理审查 pull 请求、修改代码和 merge ?

Git - 推送当前分支快捷方式

Git Directory Diff 在我的子模块中不起作用

git:比较二进制文件

git - 为什么我 pull 的时候需要一直做 `--set-upstream-to`?

git - Jenkins 管道 : How do I fetch (not pull) a different branch?

git - smartgit 分支窗口中的箭头