Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 832
And Wan Avatar asked May 15 '17 11:05

And Wan


People also ask

How do you squash a specific commit on a branch?

Git squash with a commit id The last command opens the interactive Git rebase tool which lists all of the commits in the branch. You must type the word pick next to the commit you want all others to be squashed into. Then type 'squash', or just the letter 's', next to each commit to squash.

How do you squash multiple commits in the same branch?

Another way to turn multiple commits in a feature branch into a single commit is to reset the feature branch changes in the master and commit everything again.

How do you merge all commits into one in a branch?

Another simple way to do this: go on the origin branch and do a merge --squash . This command doesn't do the "squashed" commit. when you do it, all commit messages of yourBranch will be gathered.


2 Answers

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.

like image 72
Wiktor Czajkowski Avatar answered Sep 28 '22 16:09

Wiktor Czajkowski


Since you need to squash so many commits, you can use the way below:

Assume myBranch original like:

...M---A---B---...---N---...---X  myBranch

If you need to squash commits from A to X, you just need to find the parent of commit A (as commit M in above graph), and then use the commands

git checkout myBranch
git reset --soft <commit id for M>
git commit -m 'squash commit from A to X'

Then the commits on myBranch will be (the squash commit is S):

...M---S  myBranch
like image 40
Marina Liu Avatar answered Sep 28 '22 17:09

Marina Liu