Git squash all commits in branch without conflicting

17,073

Solution 1

If you don't need the commit information, then you could just do a soft reset. Then files remain as they were and when you commit, this commit will be on top of the commit you did reset to.

To find the commit to reset to:

git merge-base HEAD BRANCH_YOU_BRANCHED_FROM

Then

git reset --soft COMMIT_HASH

Then re-craft the commit, perhaps:

git commit -am 'This is the new re-created one commit'

Solution 2

This is simlar to the answer from Rasmus but broken down into three steps that should always work:

$ git merge feature1
$ git reset --soft HEAD@{1}
$ git commit -c feature1

Explanation:

  1. merge and resolve conflicts
  2. keep changes staged but reset to old head
  3. commit all changes using commit message and author from feature branch latest commit

Solution 3

I've created a tool specifically for this task:

https://github.com/sheerun/git-squash

For example you can call following to squash all commits from "master" commit up to HEAD, no matter how many conflicts there would be along the way:

git squash master

It's basically what GitHub does when you "squash and merge" pull request.

Share:
17,073

Related videos on Youtube

Andy Ray
Author by

Andy Ray

Hello

Updated on June 10, 2022

Comments

  • Andy Ray
    Andy Ray about 2 years

    A common development workflow for us is to checkout branch b, commit a bunch to it, then squash all those commits into one (still on b).

    However, during the rebase -i process to squash all the commits, there are frequently conflicts at multiple steps.

    I essentially want to alter the branch into one commit that represents the state of the repository at the time of the final commit on b

    I've done some searching but I haven't found exactly what I'm looking for. I don't want to merge --squash because we would like to test the squashed feature branch before merging.

    • Andy Ray
      Andy Ray almost 11 years
      From that question - I do not want G to be in stable, I want it to still be on the feature branch. Not sure if i'm missing something
    • Micha Wiedenmann
      Micha Wiedenmann almost 11 years
      Couldn't you just cherry-pick G then?
    • Andy Ray
      Andy Ray almost 11 years
      Cherry pick it on what branch? I would like to keep the same branch name
    • Ajedi32
      Ajedi32 almost 10 years
      Why would there be conflicts when squashing? That doesn't make sense to me...
  • timetowonder
    timetowonder over 4 years
    Wow thanks a lot for this. Can you please explain why this doesn't work when you do just a "reset" (without --soft)?
  • Deepak
    Deepak almost 4 years
    This is really what I was looking for. Thanks.
  • Melroy van den Berg
    Melroy van den Berg over 2 years
    Default is --mixed instead of --soft. Mixed will reset the index and HEAD. Soft will only reset the HEAD. Hard reset will reset WorkingDir + Index + HEAD