Friday, January 10, 2020

How to squash commits in feature branch?

Before we move forward, lets make one thing clear:

WE SHOULD NOT SQUASH COMMITS IN LONG-LIVED BRANCHES SUCH AS MASTER OR DEVELOP OR RELEASE. SQUASHING COMMITS ARE ACCEPTABLE ONLY ON FEATURE BRANCHES.

When should you squash the commits in your feature branch?

To keep our long-lived branches (such as master or develop or release) clean, we may need to squash commits in our feature branch before we merge it into these long-lived branches.
IT IS NOT MANDATORY but can be required based on a TEAM's guidelines.

How to Squash commits in existing PR?

There might be a case where we need to squash the commits pushed to the feature branch for which a PR already exit. Here are the steps to squash all commits in the local feature branch and force update the respective origin branch:
  1. Checkout the feature branch you want to squash. Lets say branch name is feature/ticket-number-branch-name
  2. Make sure there are no un-staged files pending to be committed.
  3. Use gitk or git log to identify the number of commits need to be squashed from the HEAD. Lets say it is 5.
  4. Run rebase command:
    git rebase -i HEAD~5
  1. Replace pick with s or squash from commit number 2 to 5.
  2. Close and save.
  3. Delete all unwanted comments in your squashed commit.
  4. Use gitk to check if all commits has been squashed into one.
  5. Now force push to origin branch. Use following command:
    git push origin +feature/ticket-number-branch-name
In Step #9 we use + to force update the origin branch. Doing this we will be able to maintain all your PR comments and history.
It is recommended to squash commits before merging branch into master.

No comments:

Post a Comment