Git 如何查找分支起源的提交散列

假设我从主分支转移到了主题分支,然后对主题分支进行了一些提交。是否有一个命令告诉我主题分支源自的主分支上的提交散列?

理想情况下,我不必知道我提交了多少次(试图避免 HEAD ^ 5)。

我在谷歌上搜索了一圈,似乎找不到答案。谢谢!

35720 次浏览

You can use git reflog show --no-abbrev <branch name>. It will output all changes made to the branch, including it's creation, for example (I created branch xxx from master branch):

bdbf21b087de5aa2e78a7d793e035d8bd9ec9629 xxx@{0}: branch: Created from master

Note that this is not very reliable as reflog records can expire (90 days by default), and it seems like there is no 100% reliable way to do this.

use git merge-base master your-branch to find the best common ancestor between two branches (usually the branching point).

The only 100% reliable way to do this is to tag the beginning of your branch when you create it. The accepted answer will not work if you merge commits back to the branch you originated your new branch from. This is sometimes done for example if you are creating a stabilizing release branch and want to merge back your fixes you find during release testing back to master. A common thing to do. If you know you will never merge commits from your new branch back to the originating branch then the accepted answer will work.

If branches of interest are not yet merged, just like everyone says:

  • git merge-base branch1 branch2

If you've merged your branches (e.g. topic and master, merged either way):

  • Find where the last merge happened (that's what all the current answers suggest)
    • git merge-base topic master
    • gives you sha-of-last-merge
  • Find the two (in theory, possibly more) commits that were used for the merge:
    • git rev-list --parents -n 1 sha1-of-last-merge
    • gives you sha-of-last-merge sha-of-parent-1 sha-of-parent-2
    • we're interested in the last two
  • Take those two SHA1s of parents and repeat the process:
    • git merge-base sha-of-parent-1 sha-of-parent-2
    • if you didn't have intermediate merges, this will give you the commit where the branch was first created
    • otherwise you have to keep repeating
      • the worst part here is that there's no way to know when to stop other than looking at commit messages or apply other heuristics. If you're lucky you will eventually arrive at a commit on master than only has a single parent - thet's a natural stopping point. However, if you started your topic branch from a commit on master that had several parents (i.e. a merge commit), then no luck. Need heuristics / common sense / other knowledge.