84

Pretend I branched from my master branch to a topic branch, and then I did a few commits on my topic branch. Is there a command that tells me the commit hash on the master branch that my topic branch originated from?

Ideally, I wouldn't have to know how many commits I've made ( trying to avoid HEAD^5 ).

I've googled and SO'd around and can't seem to land on the answer. Thanks!

4

4 回答 4

81

您可以使用git reflog show --no-abbrev <branch name>. 它将输出对分支所做的所有更改,包括它的创建,例如(我xxx从分支创建了master分支):

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

请注意,这不是很可靠,因为 reflog 记录可能会过期(默认为 90 天),而且似乎没有 100% 可靠的方法可以做到这一点。

于 2010-10-22T16:45:33.207 回答
70

用于git merge-base master your-branch查找两个分支(通常是分支点)之间的最佳共同祖先。

于 2010-10-22T16:50:40.890 回答
6

唯一 100% 可靠的方法是在创建分支时标记分支的开头。如果您将提交合并回您创建新分支的分支,则接受的答案将不起作用。例如,如果您正在创建一个稳定的发布分支并希望将您在发布测试期间找到的修复合并回主控,有时会这样做。常做的事。如果您知道您永远不会将新分支中的提交合并回原始分支,那么接受的答案将起作用。

于 2018-10-30T20:26:11.270 回答
0

如果感兴趣的分支还没有合并,就像大家说的:

  • git merge-base branch1 branch2

如果您已经合并了您的分支(例如topicmaster,以任一方式合并):

  • 查找最后一次合并发生的位置(这就是所有当前答案所暗示的)
    • git merge-base topic master
    • 给你sha-of-last-merge
  • 找到用于合并的两个(理论上,可能更多)提交:
    • git rev-list --parents -n 1 sha1-of-last-merge
    • 给你sha-of-last-merge sha-of-parent-1 sha-of-parent-2
    • 我们对最后两个感兴趣
  • 取父母的这两个 SHA1 并重复该过程:
    • git merge-base sha-of-parent-1 sha-of-parent-2
    • 如果您没有中间合并,这将为您提供首次创建分支的提交
    • 否则你必须不断重复
      • 最糟糕的是,除了查看提交消息或应用其他启发式方法之外,没有办法知道何时停止。如果你幸运的话,你最终会在 master 上提交,而不是只有一个单亲 - 这是一个自然的停止点。但是,如果您从具有多个父项的提交(即合并提交)开始您的topic分支,那么就没有运气了。master需要启发式/常识/其他知识。
于 2021-10-08T21:40:02.087 回答