简体   繁体   中英

How to cleanly do a git pull-with-rebase after merging branches

Alternative title: How to squash merge commits?

I have the following state in my local repository:

      C     (origin/feature)
     /
A - B - m   (feature)
       /
  Y - Z     (master)

I've just merged changes from one branch to another (eg from master into our feature branch, or even vice versa). When I did this, commit B and Z were the most latest commits in their respective branches.

However! Dastardly Dan just pushed his change to the branch I was merging into (C). When I now try and push, I can't. I first have to fetch the changes and merge them somehow. The question is: how?

If I do a pull with rebase, I end up having to resolve all the conflicts in the merge between B & Z. If I try to merge, I end up with two merge commits, which isn't that clean, and also shouldn't be that necessary.

      C --
     /     \
A - B - m - m2
       /
  Y - Z

Is there any way of squashing m and m2 such that it looks like:

      C --
     /     \
A - B    -- m3
       /
  Y - Z

An interactive rebase obviously doesn't show the merge commits, and a cherry-pick requires me to resolve all the merge conflicts again (between B & Z, which weren't affected by C at all).

If you are acting on a feature branch, and only have local changes, I would suggest you to throw away your local merge, and re-merge from C .

# from your local 'feature' branch :
git checkout feature

# set your local branch to Dastardly Dan's version :
#    WARNING: do save (or commit) your local changes before running reset --hard,
#        they will be lost otherwise.
git reset --hard origin/feature

# you are now in 'C' state, merge master
git merge master

Another option is to ask Dan to rebase his work (commit C in your diagram) on top of your merge (commit m ) in order to reach :

A - B - m - C' <-feature, origin/feature
       /
  Y - Z <-master

In order to go from :

      C --
     /     \
A - B - m - m2
       /
  Y - Z

to:

      C --
     /     \
A - B    -- m3
       /
  Y - Z

you can use git commit-tree as suggested in this answer :

git commit-tree -p C -p Z m2^{tree}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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