Hegwin.Me

In silence I feel full; With speech I sense emptiness.

Git Squash Last Commits

Git 合并最后若干次提交

When people are working on features locally, sometimes a git commit is executed once a part of a feature is completed, which makes it easier to trace issues. But in a team, small, multiple commits are not very friendly to the rest of the team. So when we finally push code to the server or merge it into a master branch, it's best to target a task or story and combine the fragmented commits together. And squash can help us do that.

For example, let's say I'm merging the last three commits of the current branch into one commit before pushing to the server.

git rebase -i HEAD~3

But before that, it is advisable to set up the default git editor. I'm in Ubuntu, and the default editor is nano, which I'm not used to, so I'll change it to gvim:

git config --global core.editor "gvim -f"

After typing git rebase -i HEAD~3 the popup editor should look like this:

git_rebase_squash.webp

You'll see a list of the commits that need to be processed. For commits that we want to keep, we can use pick (which is the default behavior), and for commits that need to be merged, we can change the preceding pick to squash. However, there must be at least one pick or an action with the same effect as pick (i.e., the final merged destination).

As you can see from the above diagram, there are many more actions we can use at this stage:

  • pick
  • reword
  • edit
  • squash
  • fixup
  • exec

The effect of the different commands will be indicated in your editor. For example, if I need to change the commit message while merging, my approach is to use reword instead of pick:

git-reword-squash.webp

< Back