Rewriting History

In Git we can rewrite the history of our repository. But this must be handled with care. The ultimate goal is to have a clean and readable history that allows us to understand how our project evolved and makes it easy to move back and forth between versions.


To ensure this goal, our commits should not be too large, nor too small, and with meaningful messages that clearly explain what changes in that commit (what was delete, added, or modified). They should focus on one task at a time. So, for example, if implementing a new feature requires completing three steps, then there should be a branch for that feature. In this branch, we should have three commits, each representing the completion of one task. If while we are working on a task we find a bug or a typo, we should create a new task and work on it on its own branch and commits.


If the new feature is too large or complex, then it needs to be broken down into smaller iterations. Focus on making a basic functionality, and then iterate adding extra functionalities one at a time. Likewise, if a task is too complex, then it should be broken into sub-tasks and each sub-task should be developed in its own branch. Don't be afraid of your history looking like the one below. Use branches!! That's what they are there for!!

Rewriting history 1

Having said that, it is not always easy (or even possible) to maintain a clean history while working. This is where the tools for rewriting history come into play. With them, we can squash small and related commits into a single one, split large commits into smaller ones (each of which should represent a separate logic of changes). We can also use them to correct or improve commit messages. We can drop or modify commits (for example, if you forgot to include a file in a commit).


But, rewriting the history of a repository can be dangerous. So, there are two golden rules for rewriting history:

  • Always make sure that you know exactly what you are doing before doing it. If you thought you knew how to do something and now realize you didn't, or if you made a mistake while doing it and you don't know how to fix it, stop what you are doing and, before touching anything else, seek help.
  • NEVER REWRITE PUBLIC HISTORY. Public history is everything that has already been shared with other people. In essence, if it has been pushed onto a GitHub repository, then don't change it. Remember that commits are actually immutable. So when we rewrite history, what we are actually doing is telling Git to throw away a commit, and replace it with another (or others). If another person already started working from where we left off, then our changes might break their code.

This does not mean that rewriting history is a bad practice. In fact, it's a good one. Just remember doing it before you push your changes onto a public repository. This way you make sure that the history of the project is clean and clear.