Search code examples
gitversion-controlgit-mergerebase

How to squash commits in one branch?


I made a branch of trunk and been submitting/committing lots of changes. Every so often I would update the branch by merging from trunk (eg. 20 commits, then a merge-update, 20 more commits then a merge-update, etc).

Now I would like to squash everything in my branch. How can I do this (using either Git Extensions or console)?

I tried typing:

git rebase -i HEAD~200

but I don't know how many commits to squash. I tried counting the commits in Git Extensions but it's hard to see since it shows a mixture of everything from branch commits and trunk commits. The menu "Show current branch only" doesn't help.


Solution

  • To rebase all commits made since branching out from master you might use the following command:

    git rebase -i `git merge-base HEAD master`
    

    git merge-base finds the closest common ancestor between your current branch and the master (i.e. the last commit that is available on both).

    After passing it to the git rebase you get list of all commits since branching out from master (or whatever branch you will put in there) which you can freely squash.

    Note: this will not differentiate between yours and merge commits, but as far as I understand that's not what you're looking for.

    Note 2: beware that rewriting history after pushing to remote repo might require force-pushing, which is very troublesome when working on a single branch with other people.