Git rebase autosquash

A few years into using GIT, I came across a feature I had not seen before, and thought it'd be helpful to write it up, as it helps with integrating code review feedback and resending for review. The common way to do this is to make new commits, squash them down to the original commit, and repush your repo to the remote repository for further review.

The feature, which is buried a bit in the docs, helps support some of this, and is called autosquash. At a high level, it defines semantics for formatting commits related to code review feedback so they are automatically marked as "to be squashed" during your rebase.

In a nutshell, you:

  • Send your repo for code review, and say you've tagged it with "FEATURE-COMMIT" (using HEAD is fine for this, but if you have multiple commits based on code review, using a tag can be easier than having to keep track of how many commits for the rebase)
  • Integrate feedback and commit to your repo, passing --squash=FEATURE-COMMIT to git-commit.
  • Run git rebase --autosquash -i

Wala! All subsequent commits are marked squash, and, when git prompts you for the message for the new commit, it will automatically comment out code review commit messages in the updated commit message for FEATURE-COMMIT (if those code review commits only contain one line that is "squash: ...")

Example:

No alt text provided for this image

The commit log message is automatically created as "squash! <first line of commit passed to --squash>" at the beginning, which is how rebase knows to automatically mark commits as squashed. In my opinion, it's best not to add additional text to the commit for your code review commit unless you are sure the way git combines commit messages will be the way you want to structure your final commit message. You'll be able to edit the commit message at the end of the rebase (I always found how git made me comment out commit messages from squashed commits annoying and pointless).

When you do a rebase, specify --autosquash:

No alt text provided for this image

You'll see that git has automatically marked subsequent commits to the commits that your feature commit as to squash:

No alt text provided for this image

It has saved me time, when I remember to pass the command line options to commit and rebase. You can also configure autosquash during rebase to always be true using the rebase.autoSquash configuration option.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了