How do I ask git to merge branch back to parent

2019-05-22 15:56发布

Is there a way to write an alias that merges a branch back to its parent? I know I can do:

git checkout - && git merge -

But it only works in simple cases when my previous branch is the parent branch. As far as I know git does not track this kind of information because there is no branches in there. But I hope it's already implemented as a plugin or a hookset.
Thanks in advance.

2条回答
啃猪蹄的小仙女
2楼-- · 2019-05-22 16:17

As VonC said first I need to do is to find parent of the current branch. The following script mostly does what I need:

git branch | grep -v '*'|xargs -I{} sh -c ' printf "{}:"; git log --oneline `git merge-base "$(git rev-parse --abbrev-ref HEAD)" "{}"` | wc -l' | sort -t: -k +2n | tail -n 1 | sed 's/:.*//' 

What it does:

  • For each branch finds merge-base with the current branch
  • Finds branch:log-length pair maximizing log-length
  • Extracts branch name

After that one just need to checkout to it and merge previous head into it:

git checkout $parent_branch && git merge -

PS: I didn't test it on large repositories and it can behave suprisingly if exists a branch of the current branch. It needs to be fixed.

查看更多
SAY GOODBYE
3楼-- · 2019-05-22 16:23

Such an alias would involve first finding the "parent" branch.

It isn't trivial, and the question "Find the parent branch of a branch" has some good solutions.

Git’s history is based on a DAG of commits. Branches (and “refs” in general) are just transient labels that point to specific commits in the continually growing commit DAG.
As such, the relationship between branches can vary over time, but the relationship between commits does not.

Once you have the name of the parent branch, then you can use it in your alias.

查看更多
登录 后发表回答