Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to squash commits which have merge-commit in between?

I am working on a feature branch.

  1. Made several commits. Squashed commits.
  2. Pushed changes to remote branch. Got conflicts.
  3. Merged changes from master, resolved conflicts on feature branch.
    • git fetch origin master
    • git merge FETCH_HEAD
    • Resolved conflicts manually.
    • git commit
    • git push
  4. I made one more commit.

So, current commit history looks like this. From current to old:

  1. commit 3
  2. commit M yyy (Merged)
  3. commit 2

How do I squash above 3 commits into 1 before I merge my feature branch to master?

like image 656
Tyr1on Avatar asked May 09 '15 05:05

Tyr1on


People also ask

Can merge commits be squashed?

To enable commit squashing as the default option in your repository: Navigate to your chosen repository and open the Settings sub-tab. Open the General Settings page. Check the box for Squash commits on merge default enabled.

How do you squash commits between?

Git's squash commits command There is no explicit Git squash command. Instead, to squash git commits, the interactive git rebase is used. To squash all commits on a single branch, the interactive git rebase command must be passed one of two arguments: the id of the commit from which the branch split from its parent.

How would you squash multiple commits together using git merge -- squash?

In case you are using the Tower Git client, using Interactive Rebase to squash some commits is very simple: just select the commits you want to combine, right-click any of them, and select the "Squash Revisions..." option from the contextual menu.


2 Answers

You can rebase -i starting with commit 2's parent (that is, the commit on master that you branched from. You'll likely have to re-resolve conflicts when you get to the merge commit.

So if your history looks like

  * D commit 3 (HEAD)   * M merge  /| | * C commit 2 * | B commit on master |/ * A (master) 

Start with git rebase -i A. You'll see a list of commits including both master and your_branch, but not the merge commit. pick the first one (B or C, depending on timing) and squash the rest.

like image 99
Kristján Avatar answered Nov 11 '22 13:11

Kristján


You can use the tool I've created specifically for this task:

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

It's only necessary to merge master branch, and then run squashing command:

git merge master git squash master 
like image 41
sheerun Avatar answered Nov 11 '22 12:11

sheerun