Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collapsing a Group of Commits into One on Git

Tags:

git

I have the habit of making a huge number of small commits, and I'm fine with it. But I would like to, from time to time, take a bunch of those linear commits and collapse them together as just one commit with the ability to write a new commit message.

I've looked into the documentation but seemed a little to cryptic to me. Does anybody knows how to do that?

like image 696
rrb_bbr Avatar asked Jul 30 '11 15:07

rrb_bbr


People also ask

How do I combine commits?

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.

How can you move from 4 commits to one commit?

You can use git merge --squash to squash the commits into a single one while merging into the branch. All the commits in original-branch will be merged into a single one, and applied to the target-branch . Save this answer.


2 Answers

Assuming you don't care about retaining any of your existing commit messages, there's a nifty (and fast) git recipe you can use. First, make sure your branch is checked out:

git checkout <branch-to-squash> 

For safety, lets tag the current commit.

git tag my-branch-backup 

Next, move the branch HEAD back to your last good commit (without modifying the workspace or index). EDIT: The last good commit is the most recent commit on your branch that you want to retain.

git reset --soft <last-good-commit> 

Using git status, you'll notice that all changes on your feature branch are now staged. All that's left to do is ...

git commit 

This method is great for consolidating long, convoluted git histories and gnarly merges. Plus, there's no merge/rebase conflicts to resolve!

Now, if you need to retain any of your existing commit messages or do anything fancier than the above allows, you'll want to use git rebase --interactive.

Solution derived from: http://makandracards.com/makandra/527-squash-several-git-commits-into-a-single-commit

Reference: http://git-scm.com/docs/git-reset

Reference: http://git-scm.com/docs/git-rebase

like image 58
Ben Amos Avatar answered Sep 21 '22 13:09

Ben Amos


Suppose you want to rewrite the history of the tree going back until (but not including) commit a739b0d.

export EDITOR=vim # or your favorite editor git rebase a739b0d --interactive 

Be sure to read up on interactive rebasing first.

like image 24
yfeldblum Avatar answered Sep 20 '22 13:09

yfeldblum