简体   繁体   English

如何从当前分支获取git父分支名称?

[英]How to get git parent branch name from current branch?

Currently I am in a feature branch, but I don't know whether it was created from my develop or release branch.目前我在一个功能分支,但我不知道它是从我的开发分支还是发布分支创建的。

Can anyone please tell me how I can get the parent branch name from the current git branch.谁能告诉我如何从当前的 git 分支中获取父分支名称。

Given that Git uses a directed acyclic graph and usually a repo only has one root, all your branches point back to one initial commit.鉴于 Git 使用有向无环图并且通常一个 repo 只有一个根,您的所有分支都指向一个初始提交。 So what you actually want is the branch that shares the largest part of its history with your branch.因此,您真正想要的是与您的分支共享其历史记录中最大部分的分支。

You cannot just look for a branch whose HEAD is contained in your current branch's history, as this branches HEAD will most likely have moved since then.您不能只查找 HEAD 包含在当前分支历史记录中的分支,因为此分支 HEAD 很可能从那时起就移动了。

So I recommend you use git merge-base , which finds the newest common ancestor (aka fork point) of two branches or commits:所以我建议你使用git merge-base ,它可以找到两个分支或提交的最新共同祖先(又名分支点):

$ git merge-base feature develop
12345abc
$ git merge-base feature release
98765fed

This will output the two commits that appear in the history of both branches, respectively.这将分别输出出现在两个分支历史记录中的两个提交。 One of the two will be contained in both branches, so you can feed them to merge-base again to get the commit you want (or rather, the one you don't want):两者之一将包含在两个分支中,因此您可以再次将它们提供给merge-base以获得您想要的提交(或者更确切地说,您想要的提交):

git merge-base 12345abc 98765fed
98765fed

So in our example, feature was derived from develop , as the two share a commit that release does not have.因此,在我们的示例中, feature派生自develop ,因为两者共享release没有的提交。

Note that this will only work if you don't do criss-cross-merges between feature and develop.请注意,这仅在您不在功能和开发之间进行交叉合并时才有效。

So far this worked for me.到目前为止,这对我有用。 You can use this as terminal alias in Mac or any type of shortcut on Windows.您可以将其用作 Mac 中的终端别名或 Windows 上的任何类型的快捷方式。

git log --pretty=format:'%D' HEAD^ | grep 'origin/' | head -n1 | sed 's@origin/@@' | sed 's@,.*@@'

As explained in many places, it is not a direct parent, it gives you nearest branch which from current branch is created created or shares same HEAD^正如在许多地方所解释的,它不是直接父级,它为您提供最近的分支,该分支从当前分支创建或共享相同的 HEAD^

这个(来自https://hankchizljaw.com/notes/24/ )对我有用:

git show-branch -a | grep '\*' | grep -v `git rev-parse --abbrev-ref HEAD` | head -n1 | sed 's/.*\[\(.*\)\].*/\1/' | sed 's/[\^~].*//'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM