This note explains how to squash commits in Git. If you find any incorrect information, kindly correct it. Additionally, please feel free to ask any questions or leave comments if you encounter any issues.

Why we need to sqush the commit

When trying to resolve project issues, sometimes you need to commit multiple versions to record the work log. After sending the PR, the changes may not comply with the contribution rules, and you have to fix them. As a result, you end up with numerous commits that don't pertain to this particular PR, but only reflect your work log.

The project owner likely wants to concentrate on the final changes you made, rather than your work log. To address this, we need to squash the commits.

How to squash the commit

Given the git log shown below, I want to squash the commits after upstream/master into one commit.

* b536f0e (HEAD -> master, origin/master, origin/HEAD) Stop check in results
* 359eff8 CI: Enforce newline at end of files
* 4b9fbf3 Stop check in results
* 94ee595 CI: Enforce newline at end of files
* fd2b64e (upstream/master) Add preliminary contributor guide
* 7f6a7e7 CI: Enforce newline at end of files

Reset the origin/master to upstream/master

git checkout origin/master git reset --hard upstream/master git push --force

The new logs show below

* b536f0e (master) Stop check in results
* 359eff8 CI: Enforce newline at end of files
* 4b9fbf3 Stop check in results
* 94ee595 CI: Enforce newline at end of files
* fd2b64e (HEAD, upstream/master, origin/master, origin/HEAD) Add preliminary contributor guide
* 7f6a7e7 CI: Enforce newline at end of files

Rebase the commit, this is the most important step

git checkout master git rebase fd2b64e # The version of the upstream/master

Git may open the editor to allow you to choose the commit you want to keep, but by default, all of them are kept.

r Stop check in results
s CI: Enforce newline at end of files
s Stop check in results
s CI: Enforce newline at end of files

We have the option to modify actions for individual commits:

  • edit(e): This allows us to edit the information of the commit, such as the author details.
  • squash(s): We can remove this commit, but please note that the action of the first commit cannot be squashed.
  • rewrite(r): It gives us the ability to rewrite the commit.
  • pick§: This lets us keep the commit as it is.

After you have resolved the merge conflict or made any necessary changes, feel free to proceed.

git rebase --continue

The new logs show below

* b536f0e (HEAD->master) New commit
* fd2b64e (upstream/master, origin/master, origin/HEAD) Add preliminary contributor guide
* 7f6a7e7 CI: Enforce newline at end of files

Push the new commit

git push

The new logs show below

* b536f0e (HEAD->master, origin/master, origin/HEAD) New commit
* fd2b64e (upstream/master) Add preliminary contributor guide
* 7f6a7e7 CI: Enforce newline at end of files

Feel free to send your pull request to contribute to the project!