简体   繁体   中英

Git - How to squash selected commits?

I have the following git history:

        X --- X --- X --- X --- X feature_branch 
       /           /                        
X --- X --- X --- X develop

As you can see at some point the develop branch has been merged to the feature_branch. Now I want to merge feature_branch to develop and I want to have only two commits in the feature branch history:

  • commit one (squashed all feature branch commits)
  • commit two (merge develop to feature branch commit)

I have tried to use git rebase -i develop but it doesn't show merge develop to feature branch commit.

How to do it ?

Edit1 After git rebase -i HEAD~6 (6 because merge is a separate commit after feature branch commit 3, it is a little bit simplifier on the above diagram) I have something like this:

pick 1efad76 feature commit1
pick bae14d6 feature commit2
pick 3de7c48 feature commit3
pick 01dbb6a develop commit3
pick 674b2aa develop commit4
pick db5d9be feature commit4
pick 9cbe436 feature commit5

Merge commit is visible as two develop commits - develop commit3 and develop commit4. How put there "s" to achieve my goal ? Should I somehow reorder those commits ?

You should be able to achieve the intended result by doing the following:

git rebase -i HEAD~5 swap out 5 for as many commits as required

From there you'll be able to things like fixup which will squash the commit, and discard the commit's log message.

Take your time with it, make sure you read what git is telling you, and if you make a mistake - git reflog has got you covered - you can reset to any point in your history and undo many things with reflog - it's got me out of many pickles before! More info here

Once you're done with your interactive rebase, and you've got your commit history looking how you want it, you can go ahead and do a fast-forward merge on develop if you're finished with the feature (see below) - or continue with your feature until ready.

git checkout develop
git fetch
git pull
git merge --ff-only feature_branch

A pull will do a fetch automatically, but a it's a personal preference of mine to see what's being updated before I pull .

Note: if you're submitting a pull-request, then it will do some of this for you or warn if it can't and tell you what to do ;)

If you are continuing your feature, and develop is being updated often, then it's a good idea to keep your feature up to date with develop.

You can do a git rebase origin/develop or just develop - but again, it's a preference of mine to be up to date with the origin - which I will fetch first.

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