Howto keep Git history clean

As developer, we want our code to be clean and structured. The same should count for our Git history. In order to keep your git history clean, git rebase is king!

The great news is that is does not even involve a lot of changes to the existing way of working. Instead of a merging strategy on a pull request, you need to configure the repository to only allow fast-forward merge only in combination with rebase. Gitlab and Bitbucket Server provide support for this merge strategy out of the box.

This way:

  • no merge commit will be created if your source branch was not outdated.
  • if fast-forward merge is not possible, an auto rebase button is provided in case a conflict free rebase is possible and no merge commit will be created.
  • when there is a conflict. You will need to resolve the conflicts yourself localy. Resolving conflicts is something you already did before, so this should go fine as well. The biggest difference is that solving the conflicts is a multi step operation. This means that you need to solve possibly more conflicts, but always very small with all context you need.

In case you do trunk base development and you want to rebase all your code on the latest master branch:

git rebase -i origin/master --autosquash

In order to make this process very easy, you should keep your commits very small and do only what they are meant to do and nothing else. That was for me personaly the biggest game changer. But when you work with structured well defined small commits, rebasing is no rocket science. For me it even makes more sense to apply all your structured changes on to the lastest version. But the biggest benefit will be when something went wrong, because it will be much easier to track down where the issue was introduced. Also new developers will have it much easier when checking the history of the project.

Rebase has a bad reputation. It tends to be very dangerous. But when taking into account the golden rule to never rebase on shared branches, you will do no harm. You can start using it on your own branches to bring more structure in your own work. Don’t be afraid. It will be another skill you can use in your day to day development career.

Another extra safety measure you can take is to extend your force push with the --force-with-lease by default in your .gitconfig. This way, you would not overwrite the changes on the remote branch that were done by someone else in the meantime.


Easier PR review

it makes the pull request you create for your team members that do a review much easier. They can go commit by commit. Not the one big chunk of code. Also when teammates give feedback, you can easely do fixup commits on that code. When the code is actually rebased after approval. You will keep your clean well defined commit messages without the extra fixed booboo and other commit messages.

git commit --fixup REF