Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SheldonWangRJT/b106b647658a3c6c8d28f433f411dd28 to your computer and use it in GitHub Desktop.
Save SheldonWangRJT/b106b647658a3c6c8d28f433f411dd28 to your computer and use it in GitHub Desktop.
Git - How to Rebase and Squash Commits
Git - Rebase and Squashing
#iOSBySheldon
It is pretty often that you notice your feature branch has way too many commits right be fore you merge to the Master branch.
If you see your git history of your branch, it might be like:
History:
Commit xxxx1 "modified 2 more tests"
Commit xxxx2 "updated first test"
Commit xxxx3 "added class"
...
Commit xxxxx "added files"
It is pretty easy to "squash" all your commits together before you merge it to the Master branch and mess up Master's history.
To squash commits, we will be using "rebase"
Steps:
1. $ git checkout Master
2. $ git fetch
3. $ git pull
Now you have the latest Master
4. $ git checkout YourFeatureBranch
5. $ git rebase -i Master
Now vim (by default) will be opened in your terminal and a file will be shown:
----------------------------------------------------
| pick xxxx1 "modified 2 more tests"
| pick xxxx2 "updated first test"
| pick xxxx3 "added class"
| pick ....
| pick xxxxx "..."
|
| # some notes #
| # ... #
----------------------------------------------------
6. Keep the first line's "pick"
7. Change the rest pick to "squash" or "s", the updated file will be:
----------------------------------------------------
| pick xxxx1 "modified 2 more tests"
| s xxxx2 "updated first test"
| s xxxx3 "added class"
| s ....
| s xxxxx "..."
|
| # some notes #
| # ... #
----------------------------------------------------
Now we have selected first commit as our only commit to keep, and will we squash all other commits to it. In this case, only first commit's hash will be kept (xxxx1 as in my example)
8. Now we need to modify all the commit messages, vim will be automatically open again now to show all messages, like:
----------------------------------------------------
| "modified 2 more tests"
| "updated first test"
| "added class"
| ....
| "..."
|
| # some notes #
| # ... #
----------------------------------------------------
9. Write a generic message or you can even just keep all of them.
10. Your current branch is updated based on Master and you only have one commit.
Note: This is an ideal case that when you rebase from Master, there is no conflicts, if there are any conflicts, you have to solve the conflicts first, no matter you keep your changes or Master's or compiling them.
Note: Please note commit hash id is impossible to be consective numbers. I was just putting xxx1, xxx2, etc to indicates commits hash ids.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment