DEV Community

Fongoh Martin T.
Fongoh Martin T.

Posted on

Squash multiple commits into one

"Damn, your PR has 5 commits? This is not what we agreed on right? Now, i may encounter multiple merge conflicts during rebase", code review dilemma.

When working on a project with multiple developers, git and Github is one of the mostly used tools for code collaboration.

Imagine a situation where you are working on a feature and before you are done, you 5 different commits. But then, your organizational rules says each pull request must have 1 commit. This means you have to find a way to merge all the 5 commits into 1 (squash them) and then push to your branch before making a PR. Making a PR with 1 commit could also help avoid multiple issues when pulling with rebase.

The question now is, how do you bring all 5 commits into 1.

  1. On the branch which you want to make the PR from, do git log. This will show you all the commits you have made. It starts from the most recent commits right down to the last set of commits in your branch.
  2. Identify the last (from the main branch) before your first commit (needed in the pr). Example
commit 5 #hash5 (pr-branch - you are here)
commit 4 #hash4 (pr-branch)
commit 3 #hash3 (pr-branch)
commit 2 #hash2 (pr-branch)
commit 1 #hash1 (pr-branch)
commit 0 #hash0 (main-branch - you want to come here)
Enter fullscreen mode Exit fullscreen mode

Copy #hash0 and keep.

  1. You now have to soft reset (reset the commits but keep the file changes) from the current commit (#hash5) to the main commit, (#hash0) by doing git reset --soft #hash0. Replace #hash0 with the hash of commit 0.

  2. Now, if you do git status, you will see all the file changes still intact but have not yet been committed. File changes that have not been committed are in red, while file changes chat have been committed are in green (it may vary with your command line tool)

  3. Finally, you can follow the process of git add . to add the file changes, git commit -m "One commit message summarizing everything in the 5 commits" and finally, git push origin pr-branch. If you had already pushed the commits, you may need to add a -f flag in your push command.

Tahdann, there you go, you have successfully joint (squashed) all 5 commits into 1, your PR is cleaner and the dev reviewing it will be happier and likely least number of rebase merge conflicts.

If you got any other ways, please drop them in the comments section. I'll love to read and learn more about your approach.

Top comments (1)

Collapse
 
awy64 profile image
Adam Young

You can use git rebase -i to sqush,fixup,drop,reword,etc... any commits you want local, or git rebase -I \ to rebase off a branch or commit and edit the commits ahead as needed.